target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
src/containers/Menu/Menu.js | soulhat/galaxy | import React, { Component } from 'react';
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
import './Menu.css';
class Menu extends Component {
render() {
return (
<Navbar inverse collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<a href="/">Galaxy</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#">
Link
</NavItem>
<NavItem eventKey={2} href="#">
Link
</NavItem>
<NavDropdown eventKey={3} title="Dropdown" id="basic-nav-dropdown">
<MenuItem eventKey={3.1}>Action</MenuItem>
<MenuItem eventKey={3.2}>Another action</MenuItem>
<MenuItem eventKey={3.3}>Something else here</MenuItem>
<MenuItem divider />
<MenuItem eventKey={3.3}>Separated link</MenuItem>
</NavDropdown>
</Nav>
<Nav pullRight>
<NavItem eventKey={1} href="#">
Link Right
</NavItem>
<NavItem eventKey={2} href="#">
Link Right
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
export default Menu;
|
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleReversedComputerVertically.js | koenvg/Semantic-UI-React | import React from 'react'
import { Grid } from 'semantic-ui-react'
const GridExampleReversedComputerVertically = () => (
<Grid reversed='computer vertically'>
<Grid.Row>
<Grid.Column>Computer Row 4</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>Computer Row 3</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>Computer Row 2</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>Computer Row 1</Grid.Column>
</Grid.Row>
</Grid>
)
export default GridExampleReversedComputerVertically
|
app/javascript/mastodon/components/hashtag.js | masarakki/mastodon | import React from 'react';
import { Sparklines, SparklinesCurve } from 'react-sparklines';
import { Link } from 'react-router-dom';
import { FormattedMessage } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { shortNumberFormat } from '../utils/numbers';
const Hashtag = ({ hashtag }) => (
<div className='trends__item'>
<div className='trends__item__name'>
<Link to={`/timelines/tag/${hashtag.get('name')}`}>
#<span>{hashtag.get('name')}</span>
</Link>
<FormattedMessage id='trends.count_by_accounts' defaultMessage='{count} {rawCount, plural, one {person} other {people}} talking' values={{ rawCount: hashtag.getIn(['history', 0, 'accounts']), count: <strong>{shortNumberFormat(hashtag.getIn(['history', 0, 'accounts']))}</strong> }} />
</div>
<div className='trends__item__current'>
{shortNumberFormat(hashtag.getIn(['history', 0, 'uses']))}
</div>
<div className='trends__item__sparkline'>
<Sparklines width={50} height={28} data={hashtag.get('history').reverse().map(day => day.get('uses')).toArray()}>
<SparklinesCurve style={{ fill: 'none' }} />
</Sparklines>
</div>
</div>
);
Hashtag.propTypes = {
hashtag: ImmutablePropTypes.map.isRequired,
};
export default Hashtag;
|
ajax/libs/forerunnerdb/1.3.631/fdb-legacy.min.js | joeyparrish/cdnjs | !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":33,"./Shared":39}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":33,"./Shared":39}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),l=a("./Crc"),e=d.modules.Db,m=a("./Overload"),n=a("./ReactorIO"),o=new h,p.prototype.crc=l,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b(),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b);var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:f},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d(),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O=this._metrics.create("find"),P=this.primaryKey(),Q=this,R=!0,S={},T=[],U=[],V=[],W={},X={};if(b instanceof Array||(b=this.options(b)),N=function(c){return Q._match(c,a,b,"and",W)},O.start(),a){if(a instanceof Array){for(M=this,D=0;D<a.length;D++)M=M.subset(a[D],b&&b[D]?b[D]:{});return M.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(O.time("analyseQuery"),c=this._analyseQuery(Q.decouple(a),b,O),O.time("analyseQuery"),O.data("analysis",c),c.hasJoin&&c.queriesJoin){for(O.time("joinReferences"),g=0;g<c.joinsOn.length;g++)o=c.joinsOn[g],k=o.key,l=o.type,m=o.id,j=new h(c.joinQueries[k]),i=j.value(a)[0],S[m]=this._db[l](k).subset(i),delete a[c.joinQueries[k]];O.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(O.data("index.potential",c.indexMatch),O.data("index.used",c.indexMatch[0].index),O.time("indexLookup"),e=c.indexMatch[0].lookup||[],O.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(R=!1)):O.flag("usedIndex",!1),R&&(e&&e.length?(d=e.length,O.time("tableScan: "+d),e=e.filter(N)):(d=this._data.length,O.time("tableScan: "+d),e=this._data.filter(N)),O.time("tableScan: "+d)),b.$orderBy&&(O.time("sort"),e=this.sort(b.$orderBy,e),O.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(X.page=b.$page,X.pages=Math.ceil(e.length/b.$limit),X.records=e.length,b.$page&&b.$limit>0&&(O.data("cursor",X),e.splice(0,b.$page*b.$limit))),b.$skip&&(X.skip=b.$skip,e.splice(0,b.$skip),O.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(X.limit=b.$limit,e.length=b.$limit,O.data("limit",b.$limit)),b.$decouple&&(O.time("decouple"),e=this.decouple(e),O.time("decouple"),O.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(p=b.$join[f][k],l=p.$sourceType||"collection",m="$"+l+"."+k,A=k,S[m]?n=S[m]:this._db[l]&&"function"==typeof this._db[l]&&(n=this._db[l](k)),B=0;B<e.length;B++){r={},t=!1,u=!1,y="";for(q in p)if(p.hasOwnProperty(q))if(z=p[q],"$"===q.substr(0,1))switch(q){case"$where":if(!z.$query&&!z.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';z.$query&&(r=Q._resolveDynamicQuery(z.$query,e[B])),z.$options&&(s=z.$options);break;case"$as":A=z;break;case"$multi":t=z;break;case"$require":u=z;break;case"$prefix":y=z}else r[q]=Q._resolveDynamicQuery(z,e[B]);if(v=n.find(r,s),!u||u&&v[0])if("$root"===A){if(t!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';w=v[0],x=e[B];for(G in w)w.hasOwnProperty(G)&&void 0===x[y+G]&&(x[y+G]=w[G])}else e[B][A]=t===!1?v[0]:v;else T.push(e[B])}O.data("flag.join",!0)}if(T.length){for(O.time("removalQueue"),D=0;D<T.length;D++)C=e.indexOf(T[D]),C>-1&&e.splice(C,1);O.time("removalQueue")}if(b.$transform){for(O.time("transform"),D=0;D<e.length;D++)e.splice(D,1,b.$transform(e[D]));O.time("transform"),O.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(O.time("transformOut"),e=this.transformOut(e),O.time("transformOut")),O.data("results",e.length)}else e=[];if(!b.$aggregate){O.time("scanFields");for(D in b)b.hasOwnProperty(D)&&0!==D.indexOf("$")&&(1===b[D]?U.push(D):0===b[D]&&V.push(D));if(O.time("scanFields"),U.length||V.length){for(O.data("flag.limitFields",!0),O.data("limitFields.on",U),O.data("limitFields.off",V),O.time("limitFields"),D=0;D<e.length;D++){K=e[D];for(E in K)K.hasOwnProperty(E)&&(U.length&&E!==P&&-1===U.indexOf(E)&&delete K[E],V.length&&V.indexOf(E)>-1&&delete K[E])}O.time("limitFields")}if(b.$elemMatch){O.data("flag.elemMatch",!0),O.time("projection-elemMatch");for(D in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(D))for(H=new h(D),E=0;E<e.length;E++)if(I=H.value(e[E])[0],I&&I.length)for(F=0;F<I.length;F++)if(Q._match(I[F],b.$elemMatch[D],b,"",{})){H.set(e[E],D,[I[F]]);break}O.time("projection-elemMatch")}if(b.$elemsMatch){O.data("flag.elemsMatch",!0),O.time("projection-elemsMatch");for(D in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(D))for(H=new h(D),E=0;E<e.length;E++)if(I=H.value(e[E])[0],I&&I.length){for(J=[],F=0;F<I.length;F++)Q._match(I[F],b.$elemsMatch[D],b,"",{})&&J.push(I[F]);H.set(e[E],D,J)}O.time("projection-elemsMatch")}}return b.$aggregate&&(O.data("flag.aggregate",!0),O.time("aggregate"),L=new h(b.$aggregate),e=L.value(e),O.time("aggregate")),O.stop(),e.__fdbOp=O,e.$cursor=X,e},p.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},p.prototype.findOne=function(){
return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},p.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;case"2d":c=new k(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new m({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new n(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new m({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Crc":7,"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":4,"./Shared":39}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],7:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){var b=this;if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new g(a).db(this),b.emit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":4,"./Shared":39}],10:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],11:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked> All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox"> {^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")
},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":31,"./Shared":39}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":33,"./Shared":39}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":39}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":30,"./Shared":39}],18:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":31,"./Serialiser":38}],21:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":31}],23:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},
e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":31}],27:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],28:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":39}],29:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],delete this._listeners,!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./Shared":39}],30:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":33,"./Shared":39}],31:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature "'+d+'" for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],32:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.emit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":4,"./Document":9,"./Shared":39}],33:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":39}],34:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length):b.foundData=!1,c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;
if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,async:41,localforage:77}],35:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":39,pako:78}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":39,"crypto-js":50}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":39}],38:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){var b=typeof a;return"object"===b?new RegExp(a.source,a.params):"string"===b?new RegExp(a):void 0})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],39:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.631",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l=a("./Overload");d=a("./Shared");var m=function(a,b,c){this.init.apply(this,arguments)};m.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate"),this.on("joinChange",function(){d.refresh()})},d.addModule("View",m),d.mixin(m.prototype,"Mixin.Common"),d.mixin(m.prototype,"Mixin.ChainReactor"),d.mixin(m.prototype,"Mixin.Constants"),d.mixin(m.prototype,"Mixin.Triggers"),d.mixin(m.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(m.prototype,"state"),d.synthesize(m.prototype,"name"),d.synthesize(m.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),m.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},m.prototype.update=function(){this._from.update.apply(this._from,arguments)},m.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},m.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},m.prototype.find=function(a,b){return this.publicData().find(a,b)},m.prototype.findOne=function(a,b){return this.publicData().findOne(a,b)},m.prototype.findById=function(a,b){return this.publicData().findById(a,b)},m.prototype.findSub=function(a,b,c,d){return this.publicData().findSub(a,b,c,d)},m.prototype.findSubOne=function(a,b,c,d){return this.publicData().findSubOne(a,b,c,d)},m.prototype.data=function(){return this._privateData},m.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var b,d,e,f,g,h,i;if(c&&!c.isDropped()&&c._querySettings.query){if("insert"===a.type){if(b=a.data,b instanceof Array)for(f=[],i=0;i<b.length;i++)c._privateData._match(b[i],c._querySettings.query,c._querySettings.options,"and",{})&&(f.push(b[i]),g=!0);else c._privateData._match(b,c._querySettings.query,c._querySettings.options,"and",{})&&(f=b,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=c._privateData.diff(c._from.subset(c._querySettings.query,c._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=c._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=c._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var d=a.find(this._querySettings.query,this._querySettings.options);return this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},m.prototype._collectionDropped=function(a){a&&delete this._from},m.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},m.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._privateData.setData(j);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._privateData._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._privateData._updateSpliceMove(this._privateData._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._privateData.remove(a.data.query,a.options)}},m.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},m.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},m.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},m.prototype.deferEmit=function(){return this._privateData.deferEmit.apply(this._privateData,arguments)},m.prototype.distinct=function(a,b,c){var d=this.publicData();return d.distinct.apply(d,arguments)},m.prototype.primaryKey=function(){return this.publicData().primaryKey()},m.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(m.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),m.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._privateData.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._privateData.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},m.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},m.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},m.prototype.query=new l({"":function(){return this._querySettings.query},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._privateData.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._privateData.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings}}),m.prototype._joinChange=function(a,b){this.emit("joinChange")},m.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},m.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},m.prototype.pageFirst=function(){return this.page(0)},m.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},m.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},m.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},m.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},m.prototype.refresh=function(){var a,b,c,d,e,f=this;if(this._from&&(a=this.publicData(),this._privateData.remove(),b=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(b.$cursor),this._privateData.insert(b),this._privateData._data.$cursor=b.$cursor,a._data.$cursor=b.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(f.__joinChange=f.__joinChange||function(){f._joinChange()},this._joinCollections&&this._joinCollections.length)for(d=0;d<this._joinCollections.length;d++)this._db.collection(this._joinCollections[d]).off("immediateChange",f.__joinChange);for(c=this._querySettings.options.$join,this._joinCollections=[],d=0;d<c.length;d++)for(e in c[d])c[d].hasOwnProperty(e)&&this._joinCollections.push(e);if(this._joinCollections.length)for(d=0;d<this._joinCollections.length;d++)this._db.collection(this._joinCollections[d]).on("immediateChange",f.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},m.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},m.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},m.prototype.transform=function(a){var b=this;return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformEnabled?(this._publicData||(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._transformIo=new j(this._privateData,this._publicData,function(a){var c=a.data;switch(a.type){case"primaryKey":b._publicData.primaryKey(c),this.chainSend("primaryKey",c);break;case"setData":b._publicData.setData(c),this.chainSend("setData",c);break;case"insert":b._publicData.insert(c),this.chainSend("insert",c);break;case"update":b._publicData.update(c.query,c.update,c.options),this.chainSend("update",c);break;case"remove":b._publicData.remove(c.query,a.options),this.chainSend("remove",c)}})),this._publicData.primaryKey(this.privateData().primaryKey()),this._publicData.setData(this.privateData().find())):this._publicData&&(this._publicData.drop(),delete this._publicData,this._transformIo&&(this._transformIo.drop(),delete this._transformIo)),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},m.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},m.prototype.privateData=function(){return this._privateData},m.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},m.prototype.indexOf=function(){return this.publicData().indexOf.apply(this.publicData(),arguments)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new m(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof m?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new m(a).db(this),b.emit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=m},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){
c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],42:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":44}],44:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":44}],46:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":44}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":43,"./core":44}],49:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":44}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":44}],52:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":44}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":43,"./core":44}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":43,"./core":44}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":43,"./core":44}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":43,"./core":44}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":43,"./core":44}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":43,"./core":44}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":43,"./core":44}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":43,"./core":44}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":43,"./core":44}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":43,"./core":44}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;
for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":44}],68:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":44}],69:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":44,"./sha256":70}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":44}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":44,"./x64-core":75}],72:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":44,"./x64-core":75}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":44}],76:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],77:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){
return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0,function(){function a(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[h.WEBSQL]=!!a.openDatabase,c[h.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function b(a){d(this,b),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,a),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return b.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},b.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},b.prototype.driver=function(){return this._driver||null},b.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},b.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},b.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},b.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},b.prototype.supports=function(a){return!!l[a]},b.prototype._extend=function(a){e(this,a)},b.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},b.prototype._wrapLibraryMethodsWithReady=function(){for(var b=0;b<j.length;b++)a(this,j[b])},b.prototype.createInstance=function(a){return new b(a)},b}(),o=new n;b["default"]=o}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(b){return new Promise(function(c,e){var f=a([""],{type:"image/png"}),g=b.transaction([B],"readwrite");g.objectStore(B).put(f,"key"),g.oncomplete=function(){var a=b.transaction([B],"readwrite"),f=a.objectStore(B).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}}})["catch"](function(){return!1})}function f(a){return"boolean"==typeof z?Promise.resolve(z):e(a).then(function(a){return z=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(b){var d=c(atob(b.data));return a([d],{type:b.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];A||(A={});var f=A[d.name];f||(f={forages:[],db:null},A[d.name]=f),f.forages.push(this);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==this&&g.push(i.ready()["catch"](b))}var j=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,k(d)}).then(function(a){return d.db=a,n(d,c._defaultConfig.version)?l(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b in j){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function k(a){return m(a,!1)}function l(a){return m(a,!0)}function m(a,b){return new Promise(function(c,d){if(a.db){if(!b)return c(a.db);a.db.close()}var e=[a.name];b&&e.push(a.version);var f=y.open.apply(y,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(B)}catch(d){if("ConstraintError"!==d.name)throw d;x.console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result)}})}function n(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&x.console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function o(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),i(a)&&(a=h(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function p(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function q(a,b,c){var d=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){var h;d.ready().then(function(){return h=d._dbInfo,f(h.db)}).then(function(a){return!a&&b instanceof Blob?g(b):b}).then(function(b){var d=h.db.transaction(h.storeName,"readwrite"),f=d.objectStore(h.storeName);null===b&&(b=void 0);var g=f.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=g.error?g.error:g.transaction.error;e(a)}})["catch"](e)});return w(e,c),e}function r(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return w(d,b),d}function s(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return w(c,a),c}function t(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function u(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return w(d,b),d}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function w(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var x=this,y=y||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(y){var z,A,B="local-forage-detect-blob-support",C={_driver:"asyncStorage",_initStorage:j,iterate:p,getItem:o,setItem:q,removeItem:r,clear:s,length:t,key:u,keys:v};b["default"]=C}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=n.length-1;c>=0;c--){var d=n.key(c);0===d.indexOf(a)&&n.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=n.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=n.length,g=1,h=0;f>h;h++){var i=n.key(h);if(0===i.indexOf(d)){var j=n.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=n.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=n.length,d=[],e=0;c>e;e++)0===n.key(e).indexOf(a.keyPrefix)&&d.push(n.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;n.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new Promise(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{n.setItem(g.keyPrefix+a,b),e(c)}catch(h){("QuotaExceededError"===h.name||"NS_ERROR_DOM_QUOTA_REACHED"===h.name)&&f(h),f(h)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;n=this.localStorage}catch(o){return}var p={_driver:"localStorageWrapper",_initStorage:a,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};b["default"]=p}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(b){if(b.substring(0,k)!==j)return JSON.parse(b);var c,d=b.substring(w),f=b.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return a([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x=this,y={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};b["default"]=y}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(c,e){try{d.db=n(d.name,String(d.version),d.description,d.size)}catch(f){return b.setDriver(b.LOCALSTORAGE).then(function(){return b._initStorage(a)}).then(c)["catch"](e)}d.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,c()},function(a,b){e(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=this.openDatabase;if(n){var o={_driver:"webSQLStorage",_initStorage:a,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};b["default"]=o}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],78:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],82:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),
g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":81}],83:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],84:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],85:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],86:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],88:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],89:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":81}],91:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],92:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,
f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":81}],93:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]); |
test/FormGroupSpec.js | jamon/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import FormGroup from '../src/FormGroup';
import {shouldWarn} from './helpers';
describe('FormGroup', function() {
it('renders children', function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup>
<span className='child1' />
<span className='child2' />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'child1'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'child2'));
});
it('renders with form-group class', function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup>
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
});
it('renders form-group with sm or lg class when bsSize is small or large', function () {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup bsSize="small">
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-sm'));
instance = ReactTestUtils.renderIntoDocument(
<FormGroup bsSize="large">
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-lg'));
});
// This test case must come first, since the error only gets logged once.
it('throws no warning without bsSize when standalone', function () {
ReactTestUtils.renderIntoDocument(
<FormGroup standalone />
);
// Warning thrown above would lead to failure from index.
});
it('throws warning about bsSize when standalone', function () {
ReactTestUtils.renderIntoDocument(
<FormGroup standalone bsSize="large" />
);
shouldWarn('Failed propType: bsSize');
});
it('renders no form-group class when standalone', function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup standalone>
<span />
</FormGroup>
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0);
});
it('renders no form-group-* class when standalone', function () {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup standalone bsSize="large" />
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group-lg').length, 0);
});
[{
className: 'has-feedback',
props: { hasFeedback: true }
}, {
className: 'has-success',
props: { bsStyle: 'success' }
}, {
className: 'has-warning',
props: { bsStyle: 'warning' }
}, {
className: 'has-error',
props: { bsStyle: 'error' }
}, {
className: 'custom-group',
props: { groupClassName: 'custom-group' }
}
].forEach(function(testCase) {
it(`does not render ${testCase.className} class`, function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup>
<span />
</FormGroup>
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, testCase.className).length, 0);
});
it(`renders with ${testCase.className} class`, function() {
let instance = ReactTestUtils.renderIntoDocument(
<FormGroup {...testCase.props}>
<span />
</FormGroup>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, testCase.className));
});
});
});
|
ajax/libs/jquery.serialScroll/1.3.0/jquery.serialScroll.js | schoren/cdnjs | /*!
* jQuery.serialScroll
* Copyright (c) 2007-2015 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
* Licensed under MIT.
* @projectDescription Animated scrolling of series with jQuery
* @author Ariel Flesler
* @version 1.3.0
* https://github.com/flesler/jquery.serialScroll
*/
;(function($) {
var NAMESPACE = '.serialScroll';
var $serialScroll = $.serialScroll = function(settings) {
return $(window).serialScroll(settings);
};
// Many of these defaults, belong to jQuery.ScrollTo, check it's demo for an example of each option.
// @link {http://demos.flesler.com/jquery/scrollTo/ ScrollTo's Demo}
$serialScroll.defaults = {// the defaults are public and can be overriden.
duration:1000, // how long to animate.
axis:'x', // which of top and left should be scrolled
event:'click', // on which event to react.
start:0, // first element (zero-based index)
step: 1, // how many elements to scroll on each action
lock:true,// ignore events if already animating
cycle:true, // cycle endlessly (constant velocity)
constant:true // use contant speed ?
/*
navigation:null,// if specified, it's a selector to a collection of items to navigate the container
target:window, // if specified, it's a selector to the element to be scrolled.
interval:0, // it's the number of milliseconds to automatically go to the next
lazy:false,// go find the elements each time (allows AJAX or JS content, or reordering)
stop:false, // stop any previous animations to avoid queueing
force:false,// force the scroll to the first element on start ?
jump: false,// if true, when the event is triggered on an element, the pane scrolls to it
items:null, // selector to the items (relative to the matched elements)
prev:null, // selector to the 'prev' button
next:null, // selector to the 'next' button
onBefore: function() {}, // function called before scrolling, if it returns false, the event is ignored
exclude:0 // exclude the last x elements, so we cannot scroll past the end
*/
};
$.fn.serialScroll = function(options) {
return this.each(function() {
var
settings = $.extend({}, $serialScroll.defaults, options),
// this one is just to get shorter code when compressed
event = settings.event,
// ditto
step = settings.step,
// ditto
lazy = settings.lazy,
// if a target is specified, then everything's relative to 'this'.
context = settings.target ? this : document,
// the element to be scrolled (will carry all the events)
$pane = $(settings.target || this, context),
// will be reused, save it into a variable
pane = $pane[0],
// will hold a lazy list of elements
items = settings.items,
// index of the currently selected item
active = settings.start,
// boolean, do automatic scrolling or not
auto = settings.interval,
// save it now to make the code shorter
nav = settings.navigation,
// holds the interval id
timer;
// Incompatible with $().animate()
delete settings.step;
delete settings.start;
// If no match, just ignore
if (!pane) return;
// if not lazy, save the items now
if (!lazy) {
items = getItems();
}
// generate an initial call
if (settings.force || auto) {
jump({}, active);
}
// Button binding, optional
$(settings.prev||[], context).bind(event, -step, move);
$(settings.next||[], context).bind(event, step, move);
// Custom events bound to the container
if (!pane._bound_) {
$pane
// You can trigger with just 'prev'
.bind('prev'+NAMESPACE, -step, move)
// f.e: $(container).trigger('next');
.bind('next'+NAMESPACE, step, move)
// f.e: $(container).trigger('goto', 4);
.bind('goto'+NAMESPACE, jump);
}
if (auto) {
$pane
.bind('start'+NAMESPACE, function(e) {
if (!auto) {
clear();
auto = true;
next();
}
})
.bind('stop'+NAMESPACE, function() {
clear();
auto = false;
});
}
// Let serialScroll know that the index changed externally
$pane.bind('notify'+NAMESPACE, function(e, elem) {
var i = index(elem);
if (i > -1) {
active = i;
}
});
// Avoid many bindings
pane._bound_ = true;
// Can't use jump if using lazy items and a non-bubbling event
if (settings.jump) {
(lazy ? $pane : getItems()).bind(event, function(e) {
jump(e, index(e.target));
});
}
if (nav) {
nav = $(nav, context).bind(event, function(e) {
e.data = Math.round(getItems().length / nav.length) * nav.index(this);
jump(e, this);
});
}
function move(e) {
e.data += active;
jump(e, this);
}
function jump(e, pos) {
if (!$.isNumeric(pos)) {
pos = e.data;
}
var n,
// Is a real event triggering ?
real = e.type,
// Handle a possible exclude
$items = settings.exclude ? getItems().slice(0,-settings.exclude) : getItems(),
limit = $items.length - 1,
elem = $items[pos],
duration = settings.duration;
if (real) e.preventDefault();
if (auto) {
// clear any possible automatic scrolling.
clear();
timer = setTimeout(next, settings.interval);
}
// exceeded the limits
if (!elem) {
n = pos < 0 ? 0 : limit;
// we exceeded for the first time
if (active !== n) {
pos = n;
// this is a bad case
} else if (!settings.cycle) {
return;
// invert, go to the other side
} else {
pos = limit - n;
}
elem = $items[pos];
}
// no animations while busy
if (!elem || settings.lock && $pane.is(':animated') ||
real && settings.onBefore &&
// Allow implementors to cancel scrolling
settings.onBefore(e, elem, $pane, getItems(), pos) === false) return;
if (settings.stop) {
// remove all running animations
$pane.stop(true);
}
if (settings.constant) {
// keep constant velocity
duration = Math.abs(duration/step * (active - pos));
}
$pane.scrollTo(elem, duration, settings);
// in case serialScroll was called on this elemement more than once.
trigger('notify', pos);
}
function next() {
trigger('next');
}
function clear() {
clearTimeout(timer);
}
function getItems() {
return $(items, pane);
}
// I'll use the namespace to avoid conflicts
function trigger(event) {
$pane.trigger(
event+NAMESPACE,
[].slice.call(arguments,1)
);
}
function index(elem) {
// Already a number
if ($.isNumeric(elem)) {
return elem;
}
var $items = getItems(), i;
// See if it matches or one of its ancestors
while((i = $items.index(elem)) === -1 && elem !== pane) {
elem = elem.parentNode;
}
return i;
}
});
};
})(jQuery); |
misc/tabledrag.js | solnalag/sandudden | (function ($) {
/**
* Drag and drop table rows with field manipulation.
*
* Using the drupal_add_tabledrag() function, any table with weights or parent
* relationships may be made into draggable tables. Columns containing a field
* may optionally be hidden, providing a better user experience.
*
* Created tableDrag instances may be modified with custom behaviors by
* overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
* See blocks.js for an example of adding additional functionality to tableDrag.
*/
Drupal.behaviors.tableDrag = {
attach: function (context, settings) {
for (var base in settings.tableDrag) {
$('#' + base, context).once('tabledrag', function () {
// Create the new tableDrag instance. Save in the Drupal variable
// to allow other scripts access to the object.
Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]);
});
}
}
};
/**
* Constructor for the tableDrag object. Provides table and field manipulation.
*
* @param table
* DOM object for the table to be made draggable.
* @param tableSettings
* Settings for the table added via drupal_add_dragtable().
*/
Drupal.tableDrag = function (table, tableSettings) {
var self = this;
// Required object variables.
this.table = table;
this.tableSettings = tableSettings;
this.dragObject = null; // Used to hold information about a current drag operation.
this.rowObject = null; // Provides operations for row manipulation.
this.oldRowElement = null; // Remember the previous element.
this.oldY = 0; // Used to determine up or down direction from last mouse move.
this.changed = false; // Whether anything in the entire table has changed.
this.maxDepth = 0; // Maximum amount of allowed parenting.
this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table.
// Configure the scroll settings.
this.scrollSettings = { amount: 4, interval: 50, trigger: 70 };
this.scrollInterval = null;
this.scrollY = 0;
this.windowHeight = 0;
// Check this table's settings to see if there are parent relationships in
// this table. For efficiency, large sections of code can be skipped if we
// don't need to track horizontal movement and indentations.
this.indentEnabled = false;
for (var group in tableSettings) {
for (var n in tableSettings[group]) {
if (tableSettings[group][n].relationship == 'parent') {
this.indentEnabled = true;
}
if (tableSettings[group][n].limit > 0) {
this.maxDepth = tableSettings[group][n].limit;
}
}
}
if (this.indentEnabled) {
this.indentCount = 1; // Total width of indents, set in makeDraggable.
// Find the width of indentations to measure mouse movements against.
// Because the table doesn't need to start with any indentations, we
// manually append 2 indentations in the first draggable row, measure
// the offset, then remove.
var indent = Drupal.theme('tableDragIndentation');
var testRow = $('<tr/>').addClass('draggable').appendTo(table);
var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft;
testRow.remove();
}
// Make each applicable row draggable.
// Match immediate children of the parent element to allow nesting.
$('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); });
// Add a link before the table for users to show or hide weight columns.
$(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>')
.attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
.click(function () {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
self.hideColumns();
}
else {
self.showColumns();
}
return false;
})
.wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
.parent()
);
// Initialize the specified columns (for example, weight or parent columns)
// to show or hide according to user preference. This aids accessibility
// so that, e.g., screen reader users can choose to enter weight values and
// manipulate form elements directly, rather than using drag-and-drop..
self.initColumns();
// Add mouse bindings to the document. The self variable is passed along
// as event handlers do not have direct access to the tableDrag object.
$(document).bind('mousemove', function (event) { return self.dragRow(event, self); });
$(document).bind('mouseup', function (event) { return self.dropRow(event, self); });
};
/**
* Initialize columns containing form elements to be hidden by default,
* according to the settings for this tableDrag instance.
*
* Identify and mark each cell with a CSS class so we can easily toggle
* show/hide it. Finally, hide columns if user does not have a
* 'Drupal.tableDrag.showWeight' cookie.
*/
Drupal.tableDrag.prototype.initColumns = function () {
for (var group in this.tableSettings) {
// Find the first field in this group.
for (var d in this.tableSettings[group]) {
var field = $('.' + this.tableSettings[group][d].target + ':first', this.table);
if (field.length && this.tableSettings[group][d].hidden) {
var hidden = this.tableSettings[group][d].hidden;
var cell = field.closest('td');
break;
}
}
// Mark the column containing this field so it can be hidden.
if (hidden && cell[0]) {
// Add 1 to our indexes. The nth-child selector is 1 based, not 0 based.
// Match immediate children of the parent element to allow nesting.
var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1;
$('> thead > tr, > tbody > tr, > tr', this.table).each(function () {
// Get the columnIndex and adjust for any colspans in this row.
var index = columnIndex;
var cells = $(this).children();
cells.each(function (n) {
if (n < index && this.colSpan && this.colSpan > 1) {
index -= this.colSpan - 1;
}
});
if (index > 0) {
cell = cells.filter(':nth-child(' + index + ')');
if (cell[0].colSpan && cell[0].colSpan > 1) {
// If this cell has a colspan, mark it so we can reduce the colspan.
cell.addClass('tabledrag-has-colspan');
}
else {
// Mark this cell so we can hide it.
cell.addClass('tabledrag-hide');
}
}
});
}
}
// Now hide cells and reduce colspans unless cookie indicates previous choice.
// Set a cookie if it is not already present.
if ($.cookie('Drupal.tableDrag.showWeight') === null) {
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
this.hideColumns();
}
// Check cookie value and show/hide weight columns accordingly.
else {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
this.showColumns();
}
else {
this.hideColumns();
}
}
};
/**
* Hide the columns containing weight/parent form elements.
* Undo showColumns().
*/
Drupal.tableDrag.prototype.hideColumns = function () {
// Hide weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none');
// Show TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', '');
// Reduce the colspan of any effected multi-span columns.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan - 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'hide');
};
/**
* Show the columns containing weight/parent form elements
* Undo hideColumns().
*/
Drupal.tableDrag.prototype.showColumns = function () {
// Show weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', '');
// Hide TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none');
// Increase the colspan for any columns where it was previously reduced.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan + 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 1, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
// Trigger an event to allow other scripts to react to this display change.
$('table.tabledrag-processed').trigger('columnschange', 'show');
};
/**
* Find the target used within a particular row and group.
*/
Drupal.tableDrag.prototype.rowSettings = function (group, row) {
var field = $('.' + group, row);
for (var delta in this.tableSettings[group]) {
var targetClass = this.tableSettings[group][delta].target;
if (field.is('.' + targetClass)) {
// Return a copy of the row settings.
var rowSettings = {};
for (var n in this.tableSettings[group][delta]) {
rowSettings[n] = this.tableSettings[group][delta][n];
}
return rowSettings;
}
}
};
/**
* Take an item and add event handlers to make it become draggable.
*/
Drupal.tableDrag.prototype.makeDraggable = function (item) {
var self = this;
// Create the handle.
var handle = $('<a href="#" class="tabledrag-handle"><div class="handle"> </div></a>').attr('title', Drupal.t('Drag to re-order'));
// Insert the handle after indentations (if any).
if ($('td:first .indentation:last', item).length) {
$('td:first .indentation:last', item).after(handle);
// Update the total width of indentation in this entire table.
self.indentCount = Math.max($('.indentation', item).length, self.indentCount);
}
else {
$('td:first', item).prepend(handle);
}
// Add hover action for the handle.
handle.hover(function () {
self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null;
}, function () {
self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null;
});
// Add the mousedown action for the handle.
handle.mousedown(function (event) {
// Create a new dragObject recording the event information.
self.dragObject = {};
self.dragObject.initMouseOffset = self.getMouseOffset(item, event);
self.dragObject.initMouseCoords = self.mouseCoords(event);
if (self.indentEnabled) {
self.dragObject.indentMousePos = self.dragObject.initMouseCoords;
}
// If there's a lingering row object from the keyboard, remove its focus.
if (self.rowObject) {
$('a.tabledrag-handle', self.rowObject.element).blur();
}
// Create a new rowObject for manipulation of this row.
self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true);
// Save the position of the table.
self.table.topY = $(self.table).offset().top;
self.table.bottomY = self.table.topY + self.table.offsetHeight;
// Add classes to the handle and row.
$(this).addClass('tabledrag-handle-hover');
$(item).addClass('drag');
// Set the document to use the move cursor during drag.
$('body').addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'none');
}
// Hack for Konqueror, prevent the blur handler from firing.
// Konqueror always gives links focus, even after returning false on mousedown.
self.safeBlur = false;
// Call optional placeholder function.
self.onDrag();
return false;
});
// Prevent the anchor tag from jumping us to the top of the page.
handle.click(function () {
return false;
});
// Similar to the hover event, add a class when the handle is focused.
handle.focus(function () {
$(this).addClass('tabledrag-handle-hover');
self.safeBlur = true;
});
// Remove the handle class on blur and fire the same function as a mouseup.
handle.blur(function (event) {
$(this).removeClass('tabledrag-handle-hover');
if (self.rowObject && self.safeBlur) {
self.dropRow(event, self);
}
});
// Add arrow-key support to the handle.
handle.keydown(function (event) {
// If a rowObject doesn't yet exist and this isn't the tab key.
if (event.keyCode != 9 && !self.rowObject) {
self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
}
var keyChange = false;
switch (event.keyCode) {
case 37: // Left arrow.
case 63234: // Safari left arrow.
keyChange = true;
self.rowObject.indent(-1 * self.rtl);
break;
case 38: // Up arrow.
case 63232: // Safari up arrow.
var previousRow = $(self.rowObject.element).prev('tr').get(0);
while (previousRow && $(previousRow).is(':hidden')) {
previousRow = $(previousRow).prev('tr').get(0);
}
if (previousRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'up';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the previous top-level row.
var groupHeight = 0;
while (previousRow && $('.indentation', previousRow).length) {
previousRow = $(previousRow).prev('tr').get(0);
groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight;
}
if (previousRow) {
self.rowObject.swap('before', previousRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, -groupHeight);
}
}
else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) {
// Swap with the previous row (unless previous row is the first one
// and undraggable).
self.rowObject.swap('before', previousRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, -parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
case 39: // Right arrow.
case 63235: // Safari right arrow.
keyChange = true;
self.rowObject.indent(1 * self.rtl);
break;
case 40: // Down arrow.
case 63233: // Safari down arrow.
var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0);
while (nextRow && $(nextRow).is(':hidden')) {
nextRow = $(nextRow).next('tr').get(0);
}
if (nextRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'down';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the next group (necessarily a top-level one).
var groupHeight = 0;
var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
if (nextGroup) {
$(nextGroup.group).each(function () {
groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
});
var nextGroupRow = $(nextGroup.group).filter(':last').get(0);
self.rowObject.swap('after', nextGroupRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, parseInt(groupHeight, 10));
}
}
else {
// Swap with the next row.
self.rowObject.swap('after', nextRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
}
if (self.rowObject && self.rowObject.changed == true) {
$(item).addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
self.oldRowElement = item;
self.restripeTable();
self.onDrag();
}
// Returning false if we have an arrow key to prevent scrolling.
if (keyChange) {
return false;
}
});
// Compatibility addition, return false on keypress to prevent unwanted scrolling.
// IE and Safari will suppress scrolling on keydown, but all other browsers
// need to return false on keypress. http://www.quirksmode.org/js/keys.html
handle.keypress(function (event) {
switch (event.keyCode) {
case 37: // Left arrow.
case 38: // Up arrow.
case 39: // Right arrow.
case 40: // Down arrow.
return false;
}
});
};
/**
* Mousemove event handler, bound to document.
*/
Drupal.tableDrag.prototype.dragRow = function (event, self) {
if (self.dragObject) {
self.currentMouseCoords = self.mouseCoords(event);
var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y;
var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x;
// Check for row swapping and vertical scrolling.
if (y != self.oldY) {
self.rowObject.direction = y > self.oldY ? 'down' : 'up';
self.oldY = y; // Update the old value.
// Check if the window should be scrolled (and how fast).
var scrollAmount = self.checkScroll(self.currentMouseCoords.y);
// Stop any current scrolling.
clearInterval(self.scrollInterval);
// Continue scrolling if the mouse has moved in the scroll direction.
if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') {
self.setScroll(scrollAmount);
}
// If we have a valid target, perform the swap and restripe the table.
var currentRow = self.findDropTargetRow(x, y);
if (currentRow) {
if (self.rowObject.direction == 'down') {
self.rowObject.swap('after', currentRow, self);
}
else {
self.rowObject.swap('before', currentRow, self);
}
self.restripeTable();
}
}
// Similar to row swapping, handle indentations.
if (self.indentEnabled) {
var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x;
// Set the number of indentations the mouse has been moved left or right.
var indentDiff = Math.round(xDiff / self.indentAmount);
// Indent the row with our estimated diff, which may be further
// restricted according to the rows around this row.
var indentChange = self.rowObject.indent(indentDiff);
// Update table and mouse indentations.
self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl;
self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
}
return false;
}
};
/**
* Mouseup event handler, bound to document.
* Blur event handler, bound to drag handle for keyboard support.
*/
Drupal.tableDrag.prototype.dropRow = function (event, self) {
// Drop row functionality shared between mouseup and blur events.
if (self.rowObject != null) {
var droppedRow = self.rowObject.element;
// The row is already in the right place so we just release it.
if (self.rowObject.changed == true) {
// Update the fields in the dropped row.
self.updateFields(droppedRow);
// If a setting exists for affecting the entire group, update all the
// fields in the entire dragged group.
for (var group in self.tableSettings) {
var rowSettings = self.rowSettings(group, droppedRow);
if (rowSettings.relationship == 'group') {
for (var n in self.rowObject.children) {
self.updateField(self.rowObject.children[n], group);
}
}
}
self.rowObject.markChanged();
if (self.changed == false) {
$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
self.changed = true;
}
}
if (self.indentEnabled) {
self.rowObject.removeIndentClasses();
}
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
$(droppedRow).removeClass('drag').addClass('drag-previous');
self.oldRowElement = droppedRow;
self.onDrop();
self.rowObject = null;
}
// Functionality specific only to mouseup event.
if (self.dragObject != null) {
$('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover');
self.dragObject = null;
$('body').removeClass('drag');
clearInterval(self.scrollInterval);
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'block');
}
}
};
/**
* Get the mouse coordinates from the event (allowing for browser differences).
*/
Drupal.tableDrag.prototype.mouseCoords = function (event) {
if (event.pageX || event.pageY) {
return { x: event.pageX, y: event.pageY };
}
return {
x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
y: event.clientY + document.body.scrollTop - document.body.clientTop
};
};
/**
* Given a target element and a mouse event, get the mouse offset from that
* element. To do this we need the element's position and the mouse position.
*/
Drupal.tableDrag.prototype.getMouseOffset = function (target, event) {
var docPos = $(target).offset();
var mousePos = this.mouseCoords(event);
return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top };
};
/**
* Find the row the mouse is currently over. This row is then taken and swapped
* with the one being dragged.
*
* @param x
* The x coordinate of the mouse on the page (not the screen).
* @param y
* The y coordinate of the mouse on the page (not the screen).
*/
Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
var rows = $(this.table.tBodies[0].rows).not(':hidden');
for (var n = 0; n < rows.length; n++) {
var row = rows[n];
var indentDiff = 0;
var rowY = $(row).offset().top;
// Because Safari does not report offsetHeight on table rows, but does on
// table cells, grab the firstChild of the row and use that instead.
// http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
if (row.offsetHeight == 0) {
var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
}
// Other browsers.
else {
var rowHeight = parseInt(row.offsetHeight, 10) / 2;
}
// Because we always insert before, we need to offset the height a bit.
if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
if (this.indentEnabled) {
// Check that this row is not a child of the row being dragged.
for (var n in this.rowObject.group) {
if (this.rowObject.group[n] == row) {
return null;
}
}
}
else {
// Do not allow a row to be swapped with itself.
if (row == this.rowObject.element) {
return null;
}
}
// Check that swapping with this row is allowed.
if (!this.rowObject.isValidSwap(row)) {
return null;
}
// We may have found the row the mouse just passed over, but it doesn't
// take into account hidden rows. Skip backwards until we find a draggable
// row.
while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) {
row = $(row).prev('tr').get(0);
}
return row;
}
}
return null;
};
/**
* After the row is dropped, update the table fields according to the settings
* set for this table.
*
* @param changedRow
* DOM object for the row that was just dropped.
*/
Drupal.tableDrag.prototype.updateFields = function (changedRow) {
for (var group in this.tableSettings) {
// Each group may have a different setting for relationship, so we find
// the source rows for each separately.
this.updateField(changedRow, group);
}
};
/**
* After the row is dropped, update a single table field according to specific
* settings.
*
* @param changedRow
* DOM object for the row that was just dropped.
* @param group
* The settings group on which field updates will occur.
*/
Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
var rowSettings = this.rowSettings(group, changedRow);
// Set the row as its own target.
if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
var sourceRow = changedRow;
}
// Siblings are easy, check previous and next rows.
else if (rowSettings.relationship == 'sibling') {
var previousRow = $(changedRow).prev('tr').get(0);
var nextRow = $(changedRow).next('tr').get(0);
var sourceRow = changedRow;
if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
if (this.indentEnabled) {
if ($('.indentations', previousRow).length == $('.indentations', changedRow)) {
sourceRow = previousRow;
}
}
else {
sourceRow = previousRow;
}
}
else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
if (this.indentEnabled) {
if ($('.indentations', nextRow).length == $('.indentations', changedRow)) {
sourceRow = nextRow;
}
}
else {
sourceRow = nextRow;
}
}
}
// Parents, look up the tree until we find a field not in this group.
// Go up as many parents as indentations in the changed row.
else if (rowSettings.relationship == 'parent') {
var previousRow = $(changedRow).prev('tr');
while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
previousRow = previousRow.prev('tr');
}
// If we found a row.
if (previousRow.length) {
sourceRow = previousRow[0];
}
// Otherwise we went all the way to the left of the table without finding
// a parent, meaning this item has been placed at the root level.
else {
// Use the first row in the table as source, because it's guaranteed to
// be at the root level. Find the first item, then compare this row
// against it as a sibling.
sourceRow = $(this.table).find('tr.draggable:first').get(0);
if (sourceRow == this.rowObject.element) {
sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
}
var useSibling = true;
}
}
// Because we may have moved the row from one category to another,
// take a look at our sibling and borrow its sources and targets.
this.copyDragClasses(sourceRow, changedRow, group);
rowSettings = this.rowSettings(group, changedRow);
// In the case that we're looking for a parent, but the row is at the top
// of the tree, copy our sibling's values.
if (useSibling) {
rowSettings.relationship = 'sibling';
rowSettings.source = rowSettings.target;
}
var targetClass = '.' + rowSettings.target;
var targetElement = $(targetClass, changedRow).get(0);
// Check if a target element exists in this row.
if (targetElement) {
var sourceClass = '.' + rowSettings.source;
var sourceElement = $(sourceClass, sourceRow).get(0);
switch (rowSettings.action) {
case 'depth':
// Get the depth of the target row.
targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length;
break;
case 'match':
// Update the value.
targetElement.value = sourceElement.value;
break;
case 'order':
var siblings = this.rowObject.findSiblings(rowSettings);
if ($(targetElement).is('select')) {
// Get a list of acceptable values.
var values = [];
$('option', targetElement).each(function () {
values.push(this.value);
});
var maxVal = values[values.length - 1];
// Populate the values in the siblings.
$(targetClass, siblings).each(function () {
// If there are more items than possible values, assign the maximum value to the row.
if (values.length > 0) {
this.value = values.shift();
}
else {
this.value = maxVal;
}
});
}
else {
// Assume a numeric input field.
var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0;
$(targetClass, siblings).each(function () {
this.value = weight;
weight++;
});
}
break;
}
}
};
/**
* Copy all special tableDrag classes from one row's form elements to a
* different one, removing any special classes that the destination row
* may have had.
*/
Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
var sourceElement = $('.' + group, sourceRow);
var targetElement = $('.' + group, targetRow);
if (sourceElement.length && targetElement.length) {
targetElement[0].className = sourceElement[0].className;
}
};
Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
var de = document.documentElement;
var b = document.body;
var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight);
var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY));
var trigger = this.scrollSettings.trigger;
var delta = 0;
// Return a scroll speed relative to the edge of the screen.
if (cursorY - scrollY > windowHeight - trigger) {
delta = trigger / (windowHeight + scrollY - cursorY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return delta * this.scrollSettings.amount;
}
else if (cursorY - scrollY < trigger) {
delta = trigger / (cursorY - scrollY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return -delta * this.scrollSettings.amount;
}
};
Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
var self = this;
this.scrollInterval = setInterval(function () {
// Update the scroll values stored in the object.
self.checkScroll(self.currentMouseCoords.y);
var aboveTable = self.scrollY > self.table.topY;
var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
window.scrollBy(0, scrollAmount);
}
}, this.scrollSettings.interval);
};
Drupal.tableDrag.prototype.restripeTable = function () {
// :even and :odd are reversed because jQuery counts from 0 and
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table)
.removeClass('odd even')
.filter(':odd').addClass('even').end()
.filter(':even').addClass('odd');
};
/**
* Stub function. Allows a custom handler when a row begins dragging.
*/
Drupal.tableDrag.prototype.onDrag = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is dropped.
*/
Drupal.tableDrag.prototype.onDrop = function () {
return null;
};
/**
* Constructor to make a new object to manipulate a table row.
*
* @param tableRow
* The DOM element for the table row we will be manipulating.
* @param method
* The method in which this row is being moved. Either 'keyboard' or 'mouse'.
* @param indentEnabled
* Whether the containing table uses indentations. Used for optimizations.
* @param maxDepth
* The maximum amount of indentations this row may contain.
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
this.element = tableRow;
this.method = method;
this.group = [tableRow];
this.groupDepth = $('.indentation', tableRow).length;
this.changed = false;
this.table = $(tableRow).closest('table').get(0);
this.indentEnabled = indentEnabled;
this.maxDepth = maxDepth;
this.direction = ''; // Direction the row is being moved.
if (this.indentEnabled) {
this.indents = $('.indentation', tableRow).length;
this.children = this.findChildren(addClasses);
this.group = $.merge(this.group, this.children);
// Find the depth of this entire group.
for (var n = 0; n < this.group.length; n++) {
this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth);
}
}
};
/**
* Find all children of rowObject by indentation.
*
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
var parentIndentation = this.indents;
var currentRow = $(this.element, this.table).next('tr.draggable');
var rows = [];
var child = 0;
while (currentRow.length) {
var rowIndentation = $('.indentation', currentRow).length;
// A greater indentation indicates this is a child.
if (rowIndentation > parentIndentation) {
child++;
rows.push(currentRow[0]);
if (addClasses) {
$('.indentation', currentRow).each(function (indentNum) {
if (child == 1 && (indentNum == parentIndentation)) {
$(this).addClass('tree-child-first');
}
if (indentNum == parentIndentation) {
$(this).addClass('tree-child');
}
else if (indentNum > parentIndentation) {
$(this).addClass('tree-child-horizontal');
}
});
}
}
else {
break;
}
currentRow = currentRow.next('tr.draggable');
}
if (addClasses && rows.length) {
$('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last');
}
return rows;
};
/**
* Ensure that two rows are allowed to be swapped.
*
* @param row
* DOM object for the row being considered for swapping.
*/
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
if (this.indentEnabled) {
var prevRow, nextRow;
if (this.direction == 'down') {
prevRow = row;
nextRow = $(row).next('tr').get(0);
}
else {
prevRow = $(row).prev('tr').get(0);
nextRow = row;
}
this.interval = this.validIndentInterval(prevRow, nextRow);
// We have an invalid swap if the valid indentations interval is empty.
if (this.interval.min > this.interval.max) {
return false;
}
}
// Do not let an un-draggable first row have anything put before it.
if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
return false;
}
return true;
};
/**
* Perform the swap between two rows.
*
* @param position
* Whether the swap will occur 'before' or 'after' the given row.
* @param row
* DOM element what will be swapped with the row group.
*/
Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
$(row)[position](this.group);
Drupal.attachBehaviors(this.group, Drupal.settings);
this.changed = true;
this.onSwap(row);
};
/**
* Determine the valid indentations interval for the row at a given position
* in the table.
*
* @param prevRow
* DOM object for the row before the tested position
* (or null for first position in the table).
* @param nextRow
* DOM object for the row after the tested position
* (or null for last position in the table).
*/
Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
var minIndent, maxIndent;
// Minimum indentation:
// Do not orphan the next row.
minIndent = nextRow ? $('.indentation', nextRow).length : 0;
// Maximum indentation:
if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
// Do not indent:
// - the first row in the table,
// - rows dragged below a non-draggable row,
// - 'root' rows.
maxIndent = 0;
}
else {
// Do not go deeper than as a child of the previous row.
maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1);
// Limit by the maximum allowed depth for the table.
if (this.maxDepth) {
maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
}
}
return { 'min': minIndent, 'max': maxIndent };
};
/**
* Indent a row within the legal bounds of the table.
*
* @param indentDiff
* The number of additional indentations proposed for the row (can be
* positive or negative). This number will be adjusted to nearest valid
* indentation level for the row.
*/
Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
// Determine the valid indentations interval if not available yet.
if (!this.interval) {
var prevRow = $(this.element).prev('tr').get(0);
var nextRow = $(this.group).filter(':last').next('tr').get(0);
this.interval = this.validIndentInterval(prevRow, nextRow);
}
// Adjust to the nearest valid indentation.
var indent = this.indents + indentDiff;
indent = Math.max(indent, this.interval.min);
indent = Math.min(indent, this.interval.max);
indentDiff = indent - this.indents;
for (var n = 1; n <= Math.abs(indentDiff); n++) {
// Add or remove indentations.
if (indentDiff < 0) {
$('.indentation:first', this.group).remove();
this.indents--;
}
else {
$('td:first', this.group).prepend(Drupal.theme('tableDragIndentation'));
this.indents++;
}
}
if (indentDiff) {
// Update indentation for this row.
this.changed = true;
this.groupDepth += indentDiff;
this.onIndent();
}
return indentDiff;
};
/**
* Find all siblings for a row, either according to its subgroup or indentation.
* Note that the passed-in row is included in the list of siblings.
*
* @param settings
* The field settings we're using to identify what constitutes a sibling.
*/
Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
var siblings = [];
var directions = ['prev', 'next'];
var rowIndentation = this.indents;
for (var d = 0; d < directions.length; d++) {
var checkRow = $(this.element)[directions[d]]();
while (checkRow.length) {
// Check that the sibling contains a similar target field.
if ($('.' + rowSettings.target, checkRow)) {
// Either add immediately if this is a flat table, or check to ensure
// that this row has the same level of indentation.
if (this.indentEnabled) {
var checkRowIndentation = $('.indentation', checkRow).length;
}
if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) {
siblings.push(checkRow[0]);
}
else if (checkRowIndentation < rowIndentation) {
// No need to keep looking for siblings when we get to a parent.
break;
}
}
else {
break;
}
checkRow = $(checkRow)[directions[d]]();
}
// Since siblings are added in reverse order for previous, reverse the
// completed list of previous siblings. Add the current row and continue.
if (directions[d] == 'prev') {
siblings.reverse();
siblings.push(this.element);
}
}
return siblings;
};
/**
* Remove indentation helper classes from the current row group.
*/
Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
for (var n in this.children) {
$('.indentation', this.children[n])
.removeClass('tree-child')
.removeClass('tree-child-first')
.removeClass('tree-child-last')
.removeClass('tree-child-horizontal');
}
};
/**
* Add an asterisk or other marker to the changed row.
*/
Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
var marker = Drupal.theme('tableDragChangedMarker');
var cell = $('td:first', this.element);
if ($('span.tabledrag-changed', cell).length == 0) {
cell.append(marker);
}
};
/**
* Stub function. Allows a custom handler when a row is indented.
*/
Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is swapped.
*/
Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
return null;
};
Drupal.theme.prototype.tableDragChangedMarker = function () {
return '<span class="warning tabledrag-changed">*</span>';
};
Drupal.theme.prototype.tableDragIndentation = function () {
return '<div class="indentation"> </div>';
};
Drupal.theme.prototype.tableDragChangedWarning = function () {
return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>';
};
})(jQuery);
|
node_modules/reactify/node_modules/react-tools/src/utils/__tests__/Transaction-test.js | singhshashi/tweetsmart | /**
* Copyright 2013-2014, 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.
*
* @emails react-core
*/
"use strict";
var assign = require('Object.assign');
var Transaction;
var INIT_ERRORED = 'initErrored'; // Just a dummy value to check for.
describe('Transaction', function() {
beforeEach(function() {
require('mock-modules').dumpCache();
Transaction = require('Transaction');
});
/**
* We should not invoke closers for inits that failed. We should pass init
* return values to closers when those inits are successful. We should not
* invoke the actual method when any of the initializers fail.
*/
it('should invoke closers with/only-with init returns', function() {
var throwInInit = function() {
throw new Error('close[0] should receive Transaction.OBSERVED_ERROR');
};
var performSideEffect;
var dontPerformThis = function() {
performSideEffect = 'This should never be set to this';
};
/**
* New test Transaction subclass.
*/
var TestTransaction = function() {
this.reinitializeTransaction();
this.firstCloseParam = INIT_ERRORED; // WON'T be set to something else
this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
this.lastCloseParam = INIT_ERRORED; // WON'T be set to something else
};
assign(TestTransaction.prototype, Transaction.Mixin);
TestTransaction.prototype.getTransactionWrappers = function() {
return [
{
initialize: throwInInit,
close: function(initResult) {
this.firstCloseParam = initResult;
}
},
{
initialize: function() { return 'asdf'; },
close: function(initResult) {
this.secondCloseParam = initResult;
}
},
{
initialize: throwInInit,
close: function(initResult) {
this.lastCloseParam = initResult;
}
}
];
};
var transaction = new TestTransaction();
expect(function() {
transaction.perform(dontPerformThis);
}).toThrow();
expect(performSideEffect).toBe(undefined);
expect(transaction.firstCloseParam).toBe(INIT_ERRORED);
expect(transaction.secondCloseParam).toBe('asdf');
expect(transaction.lastCloseParam).toBe(INIT_ERRORED);
expect(transaction.isInTransaction()).toBe(false);
});
it('should invoke closers and wrapped method when inits success', function() {
var performSideEffect;
/**
* New test Transaction subclass.
*/
var TestTransaction = function() {
this.reinitializeTransaction();
this.firstCloseParam = INIT_ERRORED; // WILL be set to something else
this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
this.lastCloseParam = INIT_ERRORED; // WILL be set to something else
};
assign(TestTransaction.prototype, Transaction.Mixin);
TestTransaction.prototype.getTransactionWrappers = function() {
return [
{
initialize: function() {
return 'firstResult';
},
close: function(initResult) {
this.firstCloseParam = initResult;
}
},
{
initialize: function() {
return 'secondResult';
},
close: function(initResult) {
this.secondCloseParam = initResult;
}
},
{
initialize: function() {
return 'thirdResult';
},
close: function(initResult) {
this.lastCloseParam = initResult;
}
}
];
};
var transaction = new TestTransaction();
transaction.perform(function() {
performSideEffect = 'SIDE_EFFECT';
});
expect(performSideEffect).toBe('SIDE_EFFECT');
expect(transaction.firstCloseParam).toBe('firstResult');
expect(transaction.secondCloseParam).toBe('secondResult');
expect(transaction.lastCloseParam).toBe('thirdResult');
expect(transaction.isInTransaction()).toBe(false);
});
/**
* When the operation throws, the transaction should throw, but all of the
* error-free closers should execute gracefully without issue. If a closer
* throws an error, the transaction should prefer to throw the error
* encountered earlier in the operation.
*/
it('should throw when wrapped operation throws', function() {
var performSideEffect;
/**
* New test Transaction subclass.
*/
var TestTransaction = function() {
this.reinitializeTransaction();
this.firstCloseParam = INIT_ERRORED; // WILL be set to something else
this.secondCloseParam = INIT_ERRORED; // WILL be set to something else
this.lastCloseParam = INIT_ERRORED; // WILL be set to something else
};
assign(TestTransaction.prototype, Transaction.Mixin);
// Now, none of the close/inits throw, but the operation we wrap will throw.
TestTransaction.prototype.getTransactionWrappers = function() {
return [
{
initialize: function() {
return 'firstResult';
},
close: function(initResult) {
this.firstCloseParam = initResult;
}
},
{
initialize: function() {
return 'secondResult';
},
close: function(initResult) {
this.secondCloseParam = initResult;
}
},
{
initialize: function() {
return 'thirdResult';
},
close: function(initResult) {
this.lastCloseParam = initResult;
}
},
{
initialize: function() {
return 'fourthResult';
},
close: function(initResult) {
throw new Error('The transaction should throw a TypeError.');
}
}
];
};
var transaction = new TestTransaction();
expect(function() {
var isTypeError = false;
try {
transaction.perform(function() {
throw new TypeError("Thrown in main wrapped operation");
});
} catch (err) {
isTypeError = (err instanceof TypeError);
}
return isTypeError;
}()).toBe(true);
expect(performSideEffect).toBe(undefined);
expect(transaction.firstCloseParam).toBe('firstResult');
expect(transaction.secondCloseParam).toBe('secondResult');
expect(transaction.lastCloseParam).toBe('thirdResult');
expect(transaction.isInTransaction()).toBe(false);
});
it('should throw errors in transaction close', function() {
var TestTransaction = function() {
this.reinitializeTransaction();
};
assign(TestTransaction.prototype, Transaction.Mixin);
var exceptionMsg = 'This exception should throw.';
TestTransaction.prototype.getTransactionWrappers = function() {
return [
{
close: function(initResult) {
throw new Error(exceptionMsg);
}
}
];
};
var transaction = new TestTransaction();
expect(function() {
transaction.perform(function() {});
}).toThrow(exceptionMsg);
expect(transaction.isInTransaction()).toBe(false);
});
it('should allow nesting of transactions', function() {
var performSideEffect;
var nestedPerformSideEffect;
/**
* New test Transaction subclass.
*/
var TestTransaction = function() {
this.reinitializeTransaction();
this.firstCloseParam = INIT_ERRORED; // WILL be set to something else
};
assign(TestTransaction.prototype, Transaction.Mixin);
TestTransaction.prototype.getTransactionWrappers = function() {
return [
{
initialize: function() {
return 'firstResult';
},
close: function(initResult) {
this.firstCloseParam = initResult;
}
},
{
initialize: function() {
this.nestedTransaction = new NestedTransaction();
},
close: function() {
// Test performing a transaction in another transaction's close()
this.nestedTransaction.perform(function() {
nestedPerformSideEffect = 'NESTED_SIDE_EFFECT';
});
}
}
];
};
var NestedTransaction = function() {
this.reinitializeTransaction();
};
assign(NestedTransaction.prototype, Transaction.Mixin);
NestedTransaction.prototype.getTransactionWrappers = function() {
return [{
initialize: function() {
this.hasInitializedNested = true;
},
close: function() {
this.hasClosedNested = true;
}
}];
};
var transaction = new TestTransaction();
transaction.perform(function() {
performSideEffect = 'SIDE_EFFECT';
});
expect(performSideEffect).toBe('SIDE_EFFECT');
expect(nestedPerformSideEffect).toBe('NESTED_SIDE_EFFECT');
expect(transaction.firstCloseParam).toBe('firstResult');
expect(transaction.isInTransaction()).toBe(false);
expect(transaction.nestedTransaction.hasClosedNested).toBe(true);
expect(transaction.nestedTransaction.hasInitializedNested).toBe(true);
expect(transaction.nestedTransaction.isInTransaction()).toBe(false);
});
});
|
packages/material-ui-icons/legacy/SignalWifi3BarSharp.js | lgollut/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5 23.64 7z" /><path d="M3.53 10.95L12 21.5l8.47-10.55C20.04 10.62 16.81 8 12 8s-8.04 2.62-8.47 2.95z" /></React.Fragment>
, 'SignalWifi3BarSharp');
|
dist/browser-tests/ogre-tests.js | elucidata/ogre2 | (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){
module.exports= require('./lib/ogre')
},{"./lib/ogre":3}],2:[function(require,module,exports){
'use strict';
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'); } }
require('es6-collections');
var _elucidataType = require('elucidata-type');
var _elucidataType2 = _interopRequireDefault(_elucidataType);
var _util = require('./util');
var Cursor = (function () {
function Cursor(source, basePath) {
_classCallCheck(this, Cursor);
this.source = source;
this.basePath = _elucidataType2['default'].isArray(basePath) ? basePath.join('.') : basePath;
}
Cursor.prototype.scopeTo = function scopeTo(path) {
return Cursor.forPath(this.basePath + '.' + path, this.source);
};
Cursor.prototype.onChange = function onChange(handler) {
var _this = this;
onSourceChange(this.source, this.basePath, handler);
return function () {
offSourceChange(_this.source, _this.basePath, handler);
};
};
Cursor.prototype.offChange = function offChange(handler) {
offSourceChange(this.source, this.basePath, handler);
return this;
};
Cursor.prototype.getFullPath = function getFullPath(path) {
var subPath = this.basePath;
if (path) {
if (_elucidataType2['default'].isArray(path)) {
if (path.length > 0) {
subPath += '.';
subPath += path.join('.');
}
} else {
subPath += '.';
subPath += path;
}
}
return subPath;
};
Cursor.forPath = function forPath(path, source) {
return new Cursor(source, path);
};
// Just for internal, testing, usage!
Cursor.listenerInfo = function listenerInfo() {
var full = arguments[0] === undefined ? false : arguments[0];
var totalSources = _eventsForSource.size,
totalKeyWatches = 0,
totalEventHandlers = 0;
_eventsForSource.forEach(function (keyMap, source) {
Object.keys(keyMap).forEach(function (key) {
var handlers = keyMap[key];
totalKeyWatches += 1;
totalEventHandlers += handlers.length;
});
});
var report = { totalSources: totalSources, totalKeyWatches: totalKeyWatches, totalEventHandlers: totalEventHandlers };
// if( full) {
// let handlers= ( JSON.stringify(_eventsForSource))
// report.events_for_source= handlers
// console.dir( handlers)
// }
return report;
};
return Cursor;
})();
[// Build pass-thru methods...
'get', 'getPrevious', 'set', 'has', 'merge', 'push', 'unshift', 'splice', 'map', 'each', 'forEach', 'reduce', 'filter', 'find', 'indexOf', 'isUndefined', 'isNotUndefined', 'isDefined', 'isNull', 'isNotNull', 'isEmpty', 'isNotEmpty', 'isString', 'isNotString', 'isArray', 'isNotArray', 'isObject', 'isNotObject', 'isNumber', 'isNotNumber'].map(function (method) {
Cursor.prototype[method] = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var argsLen = args.length,
path = undefined,
params = undefined;
if (argsLen === 0) {
return this.source[method].call(this.source, this.basePath);
} else if (argsLen === 1) {
path = args[0];
//if( _assumedValueMethods.has( method )) {
if (_assumedValueMethods.indexOf(method) >= 0) {
return this.source[method].call(this.source, this.basePath, path);
} else {
return this.source[method].call(this.source, this.getFullPath(path));
}
} else {
path = args[0];
params = args.slice(1);
params.unshift(this.getFullPath(path));
return this.source[method].apply(this.source, params);
}
};
});
var _eventsForSource = new Map(),
_sourceHandlers = new WeakMap(),
_assumedValueMethods = ['set', 'merge', 'push', 'unshift', 'splice', 'indexOf', 'map', 'each', 'forEach', 'reduce', 'filter', 'find'];
function onSourceChange(source, key, handler) {
handleEventsFor(source);
var keyMap = _eventsForSource.get(source);
keyMap[key] = keyMap[key] || [];
keyMap[key].push(handler);
}
function offSourceChange(source, key, handler) {
var keyMap = _eventsForSource.get(source);
keyMap[key] = keyMap[key] || [];
keyMap[key].splice(keyMap[key].indexOf(handler), 1);
if (keyMap[key].length === 0) {
delete keyMap[key];
if (Object.keys(keyMap).length === 0) {
var srcHandler = _sourceHandlers.get(source);
source.offChange(srcHandler);
_sourceHandlers['delete'](source);
_eventsForSource['delete'](source);
}
}
}
function handleEventsFor(source) {
if (!_eventsForSource.has(source)) {
var handler = globalEventHandler.bind(this, source);
source.onChange(handler);
_eventsForSource.set(source, {});
_sourceHandlers.set(source, handler);
}
}
function globalEventHandler(source, changedPaths) {
if (!_eventsForSource.has(source)) {
console.log('Ghost bug: Cursor#globalEventHandler() called with a source no longer tracked!');
return;
}
var trackedMap = _eventsForSource.get(source),
trackedPaths = Object.keys(trackedMap),
callbacks = [];
if (trackedPaths && trackedPaths.length) {
for (var i = 0; i < trackedPaths.length; i++) {
var trackPath = trackedPaths[i];
for (var j = 0; j < changedPaths.length; j++) {
var changedPath = changedPaths[j];
if ((0, _util.startsWith)(changedPath, trackPath)) {
var cursor_callbacks = trackedMap[trackPath];
callbacks = callbacks.concat(cursor_callbacks);
break;
}
}
}
}
if (callbacks.length) {
callbacks.forEach(function (fn) {
fn(changedPaths);
});
}
}
module.exports = Cursor;
},{"./util":4,"elucidata-type":29,"es6-collections":30}],3:[function(require,module,exports){
/**
* Ogre 2
*/
'use strict';
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 _elucidataType = require('elucidata-type');
var _elucidataType2 = _interopRequireDefault(_elucidataType);
var _reactLibUpdate = require('react/lib/update');
var _reactLibUpdate2 = _interopRequireDefault(_reactLibUpdate);
var _reactLibObjectAssign = require('react/lib/Object.assign');
var _reactLibObjectAssign2 = _interopRequireDefault(_reactLibObjectAssign);
var _eventemitter3 = require('eventemitter3');
var _eventemitter32 = _interopRequireDefault(_eventemitter3);
var _cursor = require('./cursor');
var _cursor2 = _interopRequireDefault(_cursor);
var _util = require('./util');
var _version = require('./version');
var _version2 = _interopRequireDefault(_version);
var CHANGE_KEY = 'change',
OGRE_DEFAULTS = {
batchChanges: true,
maxHistory: 1,
strict: true
};
var Ogre = (function () {
function Ogre() {
var initialState = arguments[0] === undefined ? {} : arguments[0];
var options = arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, Ogre);
if (!this instanceof Ogre) {
return new Ogre(initialState, options);
}
this._root = initialState;
this._changedKeys = [];
this._timer = null;
this._emitter = new _eventemitter32['default']();
this.history = [];
this.options = (0, _reactLibObjectAssign2['default'])({}, OGRE_DEFAULTS, options);
// If it's a subclass that implements getInitialState()...
if ('getInitialState' in this) {
this._root = this.getInitialState(this._root);
}
}
Ogre.prototype.scopeTo = function scopeTo(path) {
return _cursor2['default'].forPath(path, this);
};
// Querying
Ogre.prototype.get = function get(path, defaultValue) {
if (path === '' || path == null) return this._root; // jshint ignore:line
var value = (0, _util.findPath)(path, this._root);
if (_elucidataType2['default'].isUndefined(value)) return defaultValue;else return value;
};
Ogre.prototype.getPrevious = function getPrevious(path) {
var step = arguments[1] === undefined ? 0 : arguments[1];
return (0, _util.findPath)(path, this.history[step] || {});
};
Ogre.prototype.map = function map(path, fn) {
return this.get(path, []).map(fn);
};
// TODO: Each returns this???
Ogre.prototype.each = function each(path, fn) {
this.get(path, []).forEach(fn);
return this;
};
Ogre.prototype.forEach = function forEach(path, fn) {
return this.each(path, fn);
};
Ogre.prototype.filter = function filter(path, fn) {
return this.get(path, []).filter(fn);
};
Ogre.prototype.reduce = function reduce(path, fn, initialValue) {
return this.get(path, []).reduce(fn, initialValue);
};
Ogre.prototype.find = function find(path, fn) {
var items = this.get(path, []),
i = undefined,
l = undefined;
for (i = 0, l = items.length; i < l; i++) {
var item = items[i];
if (fn(item) === true) {
return item;
}
}
return void 0;
};
Ogre.prototype.indexOf = function indexOf(path, test) {
return this.get(path).indexOf(test);
};
// Mutations
Ogre.prototype.set = function set(path, value) {
argCheck(arguments, 'set');
this._changeDataset(path, { $set: value }, 'object');
return this;
};
Ogre.prototype.merge = function merge(path, object) {
this._changeDataset(path, { $merge: object }, 'object');
return this;
};
Ogre.prototype.push = function push(path, array) {
if (_elucidataType2['default'].isNotArray(array)) array = [array];
this._changeDataset(path, { $push: array }, 'array');
return this;
};
Ogre.prototype.unshift = function unshift(path, array) {
if (_elucidataType2['default'].isNotArray(array)) array = [array];
this._changeDataset(path, { $unshift: array }, 'array');
return this;
};
Ogre.prototype.splice = function splice(path, start, howMany) {
for (var _len = arguments.length, items = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
items[_key - 3] = arguments[_key];
}
var spec = undefined;
if (arguments.length === 2) {
spec = { $splice: start };
} else {
spec = { $splice: [[start, howMany].concat(items)] };
}
this._changeDataset(path, spec, 'array');
return this;
};
// Observing
Ogre.prototype.onChange = function onChange(fn) {
var _this = this;
this._emitter.on(CHANGE_KEY, fn);
return function () {
_this._emitter.removeListener(CHANGE_KEY, fn);
};
};
Ogre.prototype.offChange = function offChange(fn) {
this._emitter.removeListener(CHANGE_KEY, fn);
return this;
};
// Type checking
Ogre.prototype.has = function has(path) {
return this.isNotEmpty(path);
};
Ogre.prototype.isUndefined = function isUndefined(path) {
return _elucidataType2['default'].isUndefined(this.get(path));
};
Ogre.prototype.isNotUndefined = function isNotUndefined(path) {
return _elucidataType2['default'].isNotUndefined(this.get(path));
};
Ogre.prototype.isDefined = function isDefined(path) {
return _elucidataType2['default'].isNotUndefined(this.get(path));
};
Ogre.prototype.isNull = function isNull(path) {
return _elucidataType2['default'].isNull(this.get(path));
};
Ogre.prototype.isNotNull = function isNotNull(path) {
return _elucidataType2['default'].isNotNull(this.get(path));
};
Ogre.prototype.isEmpty = function isEmpty(path) {
return _elucidataType2['default'].isEmpty(this.get(path));
};
Ogre.prototype.isNotEmpty = function isNotEmpty(path) {
return _elucidataType2['default'].isNotEmpty(this.get(path));
};
Ogre.prototype.isString = function isString(path) {
return _elucidataType2['default'].isString(this.get(path));
};
Ogre.prototype.isNotString = function isNotString(path) {
return _elucidataType2['default'].isNotString(this.get(path));
};
Ogre.prototype.isArray = function isArray(path) {
return _elucidataType2['default'].isArray(this.get(path));
};
Ogre.prototype.isNotArray = function isNotArray(path) {
return _elucidataType2['default'].isNotArray(this.get(path));
};
Ogre.prototype.isObject = function isObject(path) {
return _elucidataType2['default'].isObject(this.get(path));
};
Ogre.prototype.isNotObject = function isNotObject(path) {
return _elucidataType2['default'].isNotObject(this.get(path));
};
Ogre.prototype.isNumber = function isNumber(path) {
return _elucidataType2['default'].isNumber(this.get(path));
};
Ogre.prototype.isNotNumber = function isNotNumber(path) {
return _elucidataType2['default'].isNotNumber(this.get(path));
};
Ogre.prototype._changeDataset = function _changeDataset(path, spec, containerType) {
if (this._changedKeys.length === 0) {
this.history.unshift(this._root);
while (this.options.maxHistory >= 0 && this.history.length > this.options.maxHistory) {
this.history.pop();
}
}
if (this.options.strict === false) {
(0, _util.findPath)(path, this._root, true, containerType);
}
this._root = (0, _reactLibUpdate2['default'])(this._root, (0, _util.buildSpecGraph)(path, spec));
this._scheduleChangeEvent(path);
};
Ogre.prototype._scheduleChangeEvent = function _scheduleChangeEvent(key) {
if (_elucidataType2['default'].isArray(key)) key = key.join('.');
this._changedKeys.push(key);
if (this.options.batchChanges === true) {
if (this._timer === null) {
this._timer = setTimeout(this._sendChangeEvents.bind(this), 0);
}
} else {
this._sendChangeEvents();
}
};
Ogre.prototype._sendChangeEvents = function _sendChangeEvents() {
this._emitter.emit(CHANGE_KEY, this._changedKeys);
this._changedKeys = [];
this._timer = null;
};
Ogre.prototype._clearKeyCache = function _clearKeyCache() {
_util.keyParts.clearCache();
};
return Ogre;
})();
Ogre.version = _version2['default'];
// Helpers
function argCheck(args) {
var target = arguments[1] === undefined ? '' : arguments[1];
if (args.length < 2) {
throw new Error('Invalid ' + target + ' call: Requires path and value');
}
}
module.exports = Ogre;
},{"./cursor":2,"./util":4,"./version":5,"elucidata-type":29,"eventemitter3":31,"react/lib/Object.assign":32,"react/lib/update":35}],4:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.findPath = findPath;
exports.buildSpecGraph = buildSpecGraph;
exports.keyParts = keyParts;
exports.uid = uid;
exports.startsWith = startsWith;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _elucidataType = require('elucidata-type');
var _elucidataType2 = _interopRequireDefault(_elucidataType);
function findPath(path, source, create, containerType) {
path = path || '';
source = source || {};
create = create === true ? true : false;
if (path === '') {
return source;
}
var parts = keyParts(path),
obj = source,
key = undefined;
while (obj && parts.length) {
key = parts.shift();
if (create && _elucidataType2['default'].isUndefined(obj[key])) {
if (parts.length === 0 && containerType === 'array') {
obj[key] = [];
} else {
obj[key] = {};
}
}
obj = obj[key];
}
return obj;
}
function buildSpecGraph(path, spec) {
path = path || '';
spec = spec || {};
var graph = {};
if (path === '') return graph;
var parts = keyParts(path),
obj = graph,
key = undefined;
while (parts.length) {
key = parts.shift();
if (parts.length === 0) {
obj[key] = spec;
} else {
obj[key] = {};
}
obj = obj[key];
}
return graph;
}
function keyParts(path) {
var arr = undefined;
if (_elucidataType2['default'].isArray(path)) {
return path.concat();
}
if (arr = keyCache[path]) {
// jshint ignore:line
return arr.concat();
} else {
arr = keyCache[path] = path.split('.');
return arr.concat();
}
}
var keyCache = {
'': ['']
};
keyParts.clearCache = function () {
keyCache = {
'': ['']
};
};
var _last_id = 0;
function uid(radix) {
var now = Math.floor(new Date().getTime() / 1000);
radix = radix || 36;
while (now <= _last_id) {
now += 1;
}
_last_id = now;
return now.toString(radix);
}
/* global performance */
var now = (function () {
if (typeof performance === 'object' && performance.now) {
return performance.now.bind(performance);
} else if (Date.now) {
return Date.now.bind(Date);
} else {
return function () {
return new Date().getTime();
};
}
})();
exports.now = now;
function startsWith(haystack, needle) {
// position = position || 0;
// return haystack.lastIndexOf(needle, position) === position;
return haystack.indexOf(needle) == 0;
}
},{"elucidata-type":29}],5:[function(require,module,exports){
"use strict";
module.exports = "0.4.1";
},{}],6:[function(require,module,exports){
},{}],7:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
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 // not used by this implementation
var kMaxLength = 0x3fffffff
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
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() && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding, noZero) {
if (!(this instanceof Buffer))
return new Buffer(subject, encoding, noZero)
var type = typeof subject
// Find the length
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) { // assume object is array-like
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) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
buf = Buffer._augment(new Uint8Array(length))
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
buf = this
buf.length = length
buf._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
buf._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
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
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
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)
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
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
}
}
// must be an even number of digits
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) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
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] <= 0x7F) {
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
}
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
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] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((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] & 0x80))
return (this[offset])
return ((0xff - 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 & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : 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, 0xff, 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 = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (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, 0xffff, 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, 0xffff, 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 = 0xffffffff + 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) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0xffffffff, 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, 0xffffffff, 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, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + 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, 0x7fff, -0x8000)
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, 0x7fff, -0x8000)
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, 0x7fffffff, -0x80000000)
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, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + 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.4028234663852886e+38, -3.4028234663852886e+38)
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.7976931348623157E+308, -1.7976931348623157E+308)
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)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
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
// Copy 0 bytes; we're done
if (end === start) return
if (target.length === 0 || source.length === 0) return
// Fatal error conditions
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')
// Are we oob?
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 < 1000 || !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)
}
}
// fill(value, start=0, end=buffer.length)
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')
// Fill 0 bytes; we're done
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
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
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')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array get/set methods before overwriting
arr._get = arr.get
arr._set = arr.set
// deprecated, will be removed in node 0.13+
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) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
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 <= 0x7F) {
byteArray.push(b)
} else {
var start = i
if (b >= 0xD800 && b <= 0xDFFF) 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++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
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(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":8,"ieee754":9,"is-array":10}],8:[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 //no match
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')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
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 & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} 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) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
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)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],9:[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 & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],10:[function(require,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],11:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],12:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
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 {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],13:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],14:[function(require,module,exports){
(function (process){
// 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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
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 the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
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();
// Skip empty and invalid entries
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) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
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('/'));
};
// path.relative(from, to)
// posix version
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) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
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;
}
// String.prototype.substr - negative index don't work in IE8
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":15}],15:[function(require,module,exports){
// shim for using process in browser
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');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],16:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":17}],17:[function(require,module,exports){
(function (process){
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
forEach(objectKeys(Writable.prototype), function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(this.end.bind(this));
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
}).call(this,require('_process'))
},{"./_stream_readable":19,"./_stream_writable":21,"_process":15,"core-util-is":22,"inherits":12}],18:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":20,"core-util-is":22,"inherits":12}],19:[function(require,module,exports){
(function (process){
// 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.
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
var Stream = require('stream');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var StringDecoder;
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = false;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// In streams that never have any data, and do push(null) right away,
// the consumer can miss the 'end' event if they do some I/O before
// consuming the stream. So, we don't emit('end') until some reading
// happens.
this.calledRead = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, becuase any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (typeof chunk === 'string' && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null || chunk === undefined) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) {
state.buffer.unshift(chunk);
} else {
state.reading = false;
state.buffer.push(chunk);
}
if (state.needReadable)
emitReadable(stream);
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (n === null || isNaN(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
var state = this._readableState;
state.calledRead = true;
var nOrig = n;
var ret;
if (typeof n !== 'number' || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
ret = null;
// In cases where the decoder did not receive enough data
// to produce a full chunk, then immediately received an
// EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
// howMuchToRead will see this and coerce the amount to
// read to zero (because it's looking at the length of the
// first <Buffer > in state.buffer), and we'll end up here.
//
// This can only happen via state.decoder -- no other venue
// exists for pushing a zero-length chunk into state.buffer
// and triggering this behavior. In this case, we return our
// remaining data and end the stream, if appropriate.
if (state.length > 0 && state.decoder) {
ret = fromList(n, state);
state.length -= ret.length;
}
if (state.length === 0)
endReadable(this);
return ret;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
// if we currently have less than the highWaterMark, then also read some
if (state.length - n <= state.highWaterMark)
doRead = true;
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading)
doRead = false;
if (doRead) {
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read called its callback synchronously, then `reading`
// will be false, and we need to re-evaluate how much data we
// can return to the user.
if (doRead && !state.reading)
n = howMuchToRead(nOrig, state);
if (n > 0)
ret = fromList(n, state);
else
ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended)
state.needReadable = true;
// If we happened to read() exactly the remaining amount in the
// buffer, and the EOF has been seen at this point, then make sure
// that we emit 'end' on the very next tick.
if (state.ended && !state.endEmitted && state.length === 0)
endReadable(this);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!Buffer.isBuffer(chunk) &&
'string' !== typeof chunk &&
chunk !== null &&
chunk !== undefined &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// if we've ended and we have some data left, then emit
// 'readable' now to make sure it gets picked up.
if (state.length > 0)
emitReadable(stream);
else
endReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (state.emittedReadable)
return;
state.emittedReadable = true;
if (state.sync)
process.nextTick(function() {
emitReadable_(stream);
});
else
emitReadable_(stream);
}
function emitReadable_(stream) {
stream.emit('readable');
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
process.nextTick(function() {
maybeReadMore_(stream, state);
});
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended &&
state.length < state.highWaterMark) {
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
else
len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function(dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
dest !== process.stdout &&
dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted)
process.nextTick(endFn);
else
src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
if (readable !== src) return;
cleanup();
}
function onend() {
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
function cleanup() {
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (!dest._writableState || dest._writableState.needDrain)
ondrain();
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
unpipe();
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
}
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS.
if (!dest._events || !dest._events.error)
dest.on('error', onerror);
else if (isArray(dest._events.error))
dest._events.error.unshift(onerror);
else
dest._events.error = [onerror, dest._events.error];
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
// the handler that waits for readable events after all
// the data gets sucked out in flow.
// This would be easier to follow with a .once() handler
// in flow(), but that is too slow.
this.on('readable', pipeOnReadable);
state.flowing = true;
process.nextTick(function() {
flow(src);
});
}
return dest;
};
function pipeOnDrain(src) {
return function() {
var dest = this;
var state = src._readableState;
state.awaitDrain--;
if (state.awaitDrain === 0)
flow(src);
};
}
function flow(src) {
var state = src._readableState;
var chunk;
state.awaitDrain = 0;
function write(dest, i, list) {
var written = dest.write(chunk);
if (false === written) {
state.awaitDrain++;
}
}
while (state.pipesCount && null !== (chunk = src.read())) {
if (state.pipesCount === 1)
write(state.pipes, 0, null);
else
forEach(state.pipes, write);
src.emit('data', chunk);
// if anyone needs a drain, then we have to wait for that.
if (state.awaitDrain > 0)
return;
}
// if every destination was unpiped, either before entering this
// function, or in the while loop, then stop flowing.
//
// NB: This is a pretty rare edge case.
if (state.pipesCount === 0) {
state.flowing = false;
// if there were data event listeners added, then switch to old mode.
if (EE.listenerCount(src, 'data') > 0)
emitDataEvents(src);
return;
}
// at this point, no one needed a drain, so we just ran out of data
// on the next readable event, start it over again.
state.ranOut = true;
}
function pipeOnReadable() {
if (this._readableState.ranOut) {
this._readableState.ranOut = false;
flow(this);
}
}
Readable.prototype.unpipe = function(dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0)
return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes)
return this;
if (!dest)
dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
this.removeListener('readable', pipeOnReadable);
state.flowing = false;
if (dest)
dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
this.removeListener('readable', pipeOnReadable);
state.flowing = false;
for (var i = 0; i < len; i++)
dests[i].emit('unpipe', this);
return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1)
return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1)
state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data' && !this._readableState.flowing)
emitDataEvents(this);
if (ev === 'readable' && this.readable) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
this.read(0);
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
emitDataEvents(this);
this.read(0);
this.emit('resume');
};
Readable.prototype.pause = function() {
emitDataEvents(this, true);
this.emit('pause');
};
function emitDataEvents(stream, startPaused) {
var state = stream._readableState;
if (state.flowing) {
// https://github.com/isaacs/readable-stream/issues/16
throw new Error('Cannot switch to old mode now.');
}
var paused = startPaused || false;
var readable = false;
// convert to an old-style stream.
stream.readable = true;
stream.pipe = Stream.prototype.pipe;
stream.on = stream.addListener = Stream.prototype.on;
stream.on('readable', function() {
readable = true;
var c;
while (!paused && (null !== (c = stream.read())))
stream.emit('data', c);
if (c === null) {
readable = false;
stream._readableState.needReadable = true;
}
});
stream.pause = function() {
paused = true;
this.emit('pause');
};
stream.resume = function() {
paused = false;
if (readable)
process.nextTick(function() {
stream.emit('readable');
});
else
this.read(0);
this.emit('resume');
};
// now make it start, just in case it hadn't already.
stream.emit('readable');
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function() {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length)
self.push(chunk);
}
self.push(null);
});
stream.on('data', function(chunk) {
if (state.decoder)
chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
//if (state.objectMode && util.isNullOrUndefined(chunk))
if (state.objectMode && (chunk === null || chunk === undefined))
return;
else if (!state.objectMode && (!chunk || !chunk.length))
return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (typeof stream[i] === 'function' &&
typeof this[i] === 'undefined') {
this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments);
}}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function(ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function(n) {
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0)
return null;
if (length === 0)
ret = null;
else if (objectMode)
ret = list.shift();
else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
else
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
if (stringMode)
ret = '';
else
ret = new Buffer(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var buf = list[0];
var cpy = Math.min(n - c, buf.length);
if (stringMode)
ret += buf.slice(0, cpy);
else
buf.copy(ret, c, 0, cpy);
if (cpy < buf.length)
list[0] = buf.slice(cpy);
else
list.shift();
c += cpy;
}
}
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0)
throw new Error('endReadable called on non-empty stream');
if (!state.endEmitted && state.calledRead) {
state.ended = true;
process.nextTick(function() {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
});
}
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf (xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"_process":15,"buffer":7,"core-util-is":22,"events":11,"inherits":12,"isarray":13,"stream":27,"string_decoder/":28}],20:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined)
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
var ts = this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('finish', function() {
if ('function' === typeof this._flush)
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var rs = stream._readableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":17,"core-util-is":22,"inherits":12}],21:[function(require,module,exports){
(function (process){
// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, becuase any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!Buffer.isBuffer(chunk) &&
'string' !== typeof chunk &&
chunk !== null &&
chunk !== undefined &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (typeof cb !== 'function')
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb))
ret = writeOrBuffer(this, state, chunk, encoding, cb);
return ret;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
typeof chunk === 'string') {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
cb(er);
});
else
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished && !state.bufferProcessing && state.buffer.length)
clearBuffer(stream, state);
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
cb();
if (finished)
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
state.bufferProcessing = false;
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (typeof chunk !== 'undefined' && chunk !== null)
this.write(chunk, encoding);
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
state.finished = true;
stream.emit('finish');
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
process.nextTick(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
}).call(this,require('_process'))
},{"./_stream_duplex":17,"_process":15,"buffer":7,"core-util-is":22,"inherits":12,"stream":27}],22:[function(require,module,exports){
(function (Buffer){
// 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.
// 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);
}
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' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,require("buffer").Buffer)
},{"buffer":7}],23:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":18}],24:[function(require,module,exports){
var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":17,"./lib/_stream_passthrough.js":18,"./lib/_stream_readable.js":19,"./lib/_stream_transform.js":20,"./lib/_stream_writable.js":21,"stream":27}],25:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":20}],26:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":21}],27:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":11,"inherits":12,"readable-stream/duplex.js":16,"readable-stream/passthrough.js":23,"readable-stream/readable.js":24,"readable-stream/transform.js":25,"readable-stream/writable.js":26}],28:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":7}],29:[function(require,module,exports){
(function() {
var name, type, _elementTestRe, _fn, _i, _keys, _len, _ref, _typeList;
_typeList = "Boolean Number String Function Array Date RegExp Undefined Null NodeList".split(" ");
_elementTestRe = /element$/;
_keys = Object.keys || function(obj) {
var key, v, _results;
_results = [];
for (key in obj) {
v = obj[key];
_results.push(key);
}
return _results;
};
type = (function() {
var classToType, elemParser, name, toStr, _i, _len;
toStr = Object.prototype.toString;
elemParser = /\[object HTML(.*)\]/;
classToType = {};
for (_i = 0, _len = _typeList.length; _i < _len; _i++) {
name = _typeList[_i];
classToType["[object " + name + "]"] = name.toLowerCase();
}
return function(obj) {
var found, strType;
strType = toStr.call(obj);
if (found = classToType[strType]) {
return found;
} else if (found = strType.match(elemParser)) {
return found[1].toLowerCase();
} else {
return "object";
}
};
})();
_ref = _typeList.concat(['Object']);
_fn = function(name) {
var nameLower;
nameLower = name.toLowerCase();
type["is" + name] = function(target) {
return type(target) === nameLower;
};
return type["isNot" + name] = function(target) {
return type(target) !== nameLower;
};
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
_fn(name);
}
type.isEmpty = function(target) {
switch (type(target)) {
case 'null':
return true;
case 'undefined':
return true;
case 'string':
return target === '';
case 'object':
return _keys(target).length === 0;
case 'array':
return target.length === 0;
case 'number':
return isNaN(target);
case 'nodelist':
return target.length === 0;
default:
return false;
}
};
type.isNotEmpty = function(target) {
return !type.isEmpty(target);
};
type.isElement = function(target) {
return _elementTestRe.test(type(target));
};
type.isNotElement = function(target) {
return !type.isElement(target);
};
if (typeof module !== "undefined" && module !== null) {
module.exports = type;
} else {
this.type = type;
}
}).call(this);
},{}],30:[function(require,module,exports){
(function (global){
(function (exports) {'use strict';
//shared pointer
var i;
//shortcuts
var defineProperty = Object.defineProperty, is = function(a,b) { return isNaN(a)? isNaN(b): a === b; };
//Polyfill global objects
if (typeof WeakMap == 'undefined') {
exports.WeakMap = createCollection({
// WeakMap#delete(key:void*):boolean
'delete': sharedDelete,
// WeakMap#clear():
clear: sharedClear,
// WeakMap#get(key:void*):void*
get: sharedGet,
// WeakMap#has(key:void*):boolean
has: mapHas,
// WeakMap#set(key:void*, value:void*):void
set: sharedSet
}, true);
}
if (typeof Map == 'undefined') {
exports.Map = createCollection({
// WeakMap#delete(key:void*):boolean
'delete': sharedDelete,
//:was Map#get(key:void*[, d3fault:void*]):void*
// Map#has(key:void*):boolean
has: mapHas,
// Map#get(key:void*):boolean
get: sharedGet,
// Map#set(key:void*, value:void*):void
set: sharedSet,
// Map#keys(void):Iterator
keys: sharedKeys,
// Map#values(void):Iterator
values: sharedValues,
// Map#entries(void):Iterator
entries: mapEntries,
// Map#forEach(callback:Function, context:void*):void ==> callback.call(context, key, value, mapObject) === not in specs`
forEach: sharedForEach,
// Map#clear():
clear: sharedClear
});
}
if (typeof Set == 'undefined') {
exports.Set = createCollection({
// Set#has(value:void*):boolean
has: setHas,
// Set#add(value:void*):boolean
add: sharedAdd,
// Set#delete(key:void*):boolean
'delete': sharedDelete,
// Set#clear():
clear: sharedClear,
// Set#keys(void):Iterator
keys: sharedValues, // specs actually say "the same function object as the initial value of the values property"
// Set#values(void):Iterator
values: sharedValues,
// Set#entries(void):Iterator
entries: setEntries,
// Set#forEach(callback:Function, context:void*):void ==> callback.call(context, value, index) === not in specs
forEach: sharedSetIterate
});
}
if (typeof WeakSet == 'undefined') {
exports.WeakSet = createCollection({
// WeakSet#delete(key:void*):boolean
'delete': sharedDelete,
// WeakSet#add(value:void*):boolean
add: sharedAdd,
// WeakSet#clear():
clear: sharedClear,
// WeakSet#has(value:void*):boolean
has: setHas
}, true);
}
/**
* ES6 collection constructor
* @return {Function} a collection class
*/
function createCollection(proto, objectOnly){
function Collection(a){
if (!this || this.constructor !== Collection) return new Collection(a);
this._keys = [];
this._values = [];
this.objectOnly = objectOnly;
//parse initial iterable argument passed
if (a) init.call(this, a);
}
//define size for non object-only collections
if (!objectOnly) {
defineProperty(proto, 'size', {
get: sharedSize
});
}
//set prototype
proto.constructor = Collection;
Collection.prototype = proto;
return Collection;
}
/** parse initial iterable argument passed */
function init(a){
var i;
//init Set argument, like `[1,2,3,{}]`
if (this.add)
a.forEach(this.add, this);
//init Map argument like `[[1,2], [{}, 4]]`
else
a.forEach(function(a){this.set(a[0],a[1])}, this);
}
/** delete */
function sharedDelete(key) {
if (this.has(key)) {
this._keys.splice(i, 1);
this._values.splice(i, 1);
}
// Aurora here does it while Canary doesn't
return -1 < i;
};
function sharedGet(key) {
return this.has(key) ? this._values[i] : undefined;
}
function has(list, key) {
if (this.objectOnly && key !== Object(key))
throw new TypeError("Invalid value used as weak collection key");
//NaN or 0 passed
if (key != key || key === 0) for (i = list.length; i-- && !is(list[i], key);){}
else i = list.indexOf(key);
return -1 < i;
}
function setHas(value) {
return has.call(this, this._values, value);
}
function mapHas(value) {
return has.call(this, this._keys, value);
}
/** @chainable */
function sharedSet(key, value) {
this.has(key) ?
this._values[i] = value
:
this._values[this._keys.push(key) - 1] = value
;
return this;
}
/** @chainable */
function sharedAdd(value) {
if (!this.has(value)) this._values.push(value);
return this;
}
function sharedClear() {
this._values.length = 0;
}
/** keys, values, and iterate related methods */
function sharedKeys() {
return sharedIterator(this._keys);
}
function sharedValues() {
return sharedIterator(this._values);
}
function mapEntries() {
return sharedIterator(this._keys, this._values);
}
function setEntries() {
return sharedIterator(this._values, this._values);
}
function sharedIterator(array, array2) {
var j = 0, done = false;
return {
next: function() {
var v;
if (!done && j < array.length) {
v = array2 ? [array[j], array2[j]]: array[j];
j += 1;
} else {
done = true;
}
return { done: done, value: v };
}
};
}
function sharedSize() {
return this._values.length;
}
function sharedForEach(callback, context) {
var self = this;
var values = self._values.slice();
self._keys.slice().forEach(function(key, n){
callback.call(context, values[n], key, self);
});
}
function sharedSetIterate(callback, context) {
var self = this;
self._values.slice().forEach(function(value){
callback.call(context, value, value, self);
});
}
})(typeof exports != 'undefined' && typeof global != 'undefined' ? global : window );
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],31:[function(require,module,exports){
'use strict';
//
// We store our EE objects in a plain object whose properties are event names.
// If `Object.create(null)` is not supported we prefix the event names with a
// `~` to make sure that the built-in object properties are not overridden or
// used as an attack vector.
// We also assume that `Object.create(null)` is available when the event name
// is an ES6 Symbol.
//
var prefix = typeof Object.create !== 'function' ? '~' : false;
/**
* Representation of a single EventEmitter function.
*
* @param {Function} fn Event handler to be called.
* @param {Mixed} context Context for function execution.
* @param {Boolean} once Only emit once
* @api private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Minimal EventEmitter interface that is molded against the Node.js
* EventEmitter interface.
*
* @constructor
* @api public
*/
function EventEmitter() { /* Nothing to set */ }
/**
* Holds the assigned EventEmitters by name.
*
* @type {Object}
* @private
*/
EventEmitter.prototype._events = undefined;
/**
* Return a list of assigned event listeners.
*
* @param {String} event The events that should be listed.
* @param {Boolean} exists We only need to know if there are listeners.
* @returns {Array|Boolean}
* @api public
*/
EventEmitter.prototype.listeners = function listeners(event, exists) {
var evt = prefix ? prefix + event : event
, available = this._events && this._events[evt];
if (exists) return !!available;
if (!available) return [];
if (this._events[evt].fn) return [this._events[evt].fn];
for (var i = 0, l = this._events[evt].length, ee = new Array(l); i < l; i++) {
ee[i] = this._events[evt][i].fn;
}
return ee;
};
/**
* Emit an event to all registered event listeners.
*
* @param {String} event The name of the event.
* @returns {Boolean} Indication if we've emitted an event.
* @api public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events || !this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if ('function' === typeof listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Register a new EventListener for the given event.
*
* @param {String} event Name of the event.
* @param {Functon} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
var listener = new EE(fn, context || this)
, evt = prefix ? prefix + event : event;
if (!this._events) this._events = prefix ? {} : Object.create(null);
if (!this._events[evt]) this._events[evt] = listener;
else {
if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [
this._events[evt], listener
];
}
return this;
};
/**
* Add an EventListener that's only called once.
*
* @param {String} event Name of the event.
* @param {Function} fn Callback function.
* @param {Mixed} context The context of the function.
* @api public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
var listener = new EE(fn, context || this, true)
, evt = prefix ? prefix + event : event;
if (!this._events) this._events = prefix ? {} : Object.create(null);
if (!this._events[evt]) this._events[evt] = listener;
else {
if (!this._events[evt].fn) this._events[evt].push(listener);
else this._events[evt] = [
this._events[evt], listener
];
}
return this;
};
/**
* Remove event listeners.
*
* @param {String} event The event we want to remove.
* @param {Function} fn The listener that we need to find.
* @param {Mixed} context Only remove listeners matching this context.
* @param {Boolean} once Only remove once listeners.
* @api public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events || !this._events[evt]) return this;
var listeners = this._events[evt]
, events = [];
if (fn) {
if (listeners.fn) {
if (
listeners.fn !== fn
|| (once && !listeners.once)
|| (context && listeners.context !== context)
) {
events.push(listeners);
}
} else {
for (var i = 0, length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn
|| (once && !listeners[i].once)
|| (context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) {
this._events[evt] = events.length === 1 ? events[0] : events;
} else {
delete this._events[evt];
}
return this;
};
/**
* Remove all listeners or only the listeners for the specified event.
*
* @param {String} event The event want to remove all listeners for.
* @api public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
if (!this._events) return this;
if (event) delete this._events[prefix ? prefix + event : event];
else this._events = prefix ? {} : Object.create(null);
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// This function doesn't apply anymore.
//
EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
return this;
};
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Expose the module.
//
module.exports = EventEmitter;
},{}],32:[function(require,module,exports){
/**
* Copyright 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
};
module.exports = assign;
},{}],33:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
"use strict";
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if ("production" !== process.env.NODE_ENV) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
}).call(this,require('_process'))
},{"_process":15}],34:[function(require,module,exports){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without loosing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
},{}],35:[function(require,module,exports){
(function (process){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule update
*/
"use strict";
var assign = require("./Object.assign");
var keyOf = require("./keyOf");
var invariant = require("./invariant");
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return assign(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = keyOf({$push: null});
var COMMAND_UNSHIFT = keyOf({$unshift: null});
var COMMAND_SPLICE = keyOf({$splice: null});
var COMMAND_SET = keyOf({$set: null});
var COMMAND_MERGE = keyOf({$merge: null});
var COMMAND_APPLY = keyOf({$apply: null});
var ALL_COMMANDS_LIST = [
COMMAND_PUSH,
COMMAND_UNSHIFT,
COMMAND_SPLICE,
COMMAND_SET,
COMMAND_MERGE,
COMMAND_APPLY
];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function(command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
("production" !== process.env.NODE_ENV ? invariant(
Array.isArray(value),
'update(): expected target of %s to be an array; got %s.',
command,
value
) : invariant(Array.isArray(value)));
var specValue = spec[command];
("production" !== process.env.NODE_ENV ? invariant(
Array.isArray(specValue),
'update(): expected spec of %s to be an array; got %s. ' +
'Did you forget to wrap your parameter in an array?',
command,
specValue
) : invariant(Array.isArray(specValue)));
}
function update(value, spec) {
("production" !== process.env.NODE_ENV ? invariant(
typeof spec === 'object',
'update(): You provided a key path to update() that did not contain one ' +
'of %s. Did you forget to include {%s: ...}?',
ALL_COMMANDS_LIST.join(', '),
COMMAND_SET
) : invariant(typeof spec === 'object'));
if (spec.hasOwnProperty(COMMAND_SET)) {
("production" !== process.env.NODE_ENV ? invariant(
Object.keys(spec).length === 1,
'Cannot have more than one key in an object with %s',
COMMAND_SET
) : invariant(Object.keys(spec).length === 1));
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (spec.hasOwnProperty(COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
("production" !== process.env.NODE_ENV ? invariant(
mergeObj && typeof mergeObj === 'object',
'update(): %s expects a spec of type \'object\'; got %s',
COMMAND_MERGE,
mergeObj
) : invariant(mergeObj && typeof mergeObj === 'object'));
("production" !== process.env.NODE_ENV ? invariant(
nextValue && typeof nextValue === 'object',
'update(): %s expects a target of type \'object\'; got %s',
COMMAND_MERGE,
nextValue
) : invariant(nextValue && typeof nextValue === 'object'));
assign(nextValue, spec[COMMAND_MERGE]);
}
if (spec.hasOwnProperty(COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function(item) {
nextValue.push(item);
});
}
if (spec.hasOwnProperty(COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function(item) {
nextValue.unshift(item);
});
}
if (spec.hasOwnProperty(COMMAND_SPLICE)) {
("production" !== process.env.NODE_ENV ? invariant(
Array.isArray(value),
'Expected %s target to be an array; got %s',
COMMAND_SPLICE,
value
) : invariant(Array.isArray(value)));
("production" !== process.env.NODE_ENV ? invariant(
Array.isArray(spec[COMMAND_SPLICE]),
'update(): expected spec of %s to be an array of arrays; got %s. ' +
'Did you forget to wrap your parameters in an array?',
COMMAND_SPLICE,
spec[COMMAND_SPLICE]
) : invariant(Array.isArray(spec[COMMAND_SPLICE])));
spec[COMMAND_SPLICE].forEach(function(args) {
("production" !== process.env.NODE_ENV ? invariant(
Array.isArray(args),
'update(): expected spec of %s to be an array of arrays; got %s. ' +
'Did you forget to wrap your parameters in an array?',
COMMAND_SPLICE,
spec[COMMAND_SPLICE]
) : invariant(Array.isArray(args)));
nextValue.splice.apply(nextValue, args);
});
}
if (spec.hasOwnProperty(COMMAND_APPLY)) {
("production" !== process.env.NODE_ENV ? invariant(
typeof spec[COMMAND_APPLY] === 'function',
'update(): expected spec of %s to be a function; got %s.',
COMMAND_APPLY,
spec[COMMAND_APPLY]
) : invariant(typeof spec[COMMAND_APPLY] === 'function'));
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
}).call(this,require('_process'))
},{"./Object.assign":32,"./invariant":33,"./keyOf":34,"_process":15}],36:[function(require,module,exports){
(function (process){
var defined = require('defined');
var createDefaultStream = require('./lib/default_stream');
var Test = require('./lib/test');
var createResult = require('./lib/results');
var through = require('through');
var canEmitExit = typeof process !== 'undefined' && process
&& typeof process.on === 'function' && process.browser !== true
;
var canExit = typeof process !== 'undefined' && process
&& typeof process.exit === 'function'
;
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
exports = module.exports = (function () {
var harness;
var lazyLoad = function () {
return getHarness().apply(this, arguments);
};
lazyLoad.only = function () {
return getHarness().only.apply(this, arguments);
};
lazyLoad.createStream = function (opts) {
if (!opts) opts = {};
if (!harness) {
var output = through();
getHarness({ stream: output, objectMode: opts.objectMode });
return output;
}
return harness.createStream(opts);
};
return lazyLoad
function getHarness (opts) {
if (!opts) opts = {};
opts.autoclose = !canEmitExit;
if (!harness) harness = createExitHarness(opts);
return harness;
}
})();
function createExitHarness (conf) {
if (!conf) conf = {};
var harness = createHarness({
autoclose: defined(conf.autoclose, false)
});
var stream = harness.createStream({ objectMode: conf.objectMode });
var es = stream.pipe(conf.stream || createDefaultStream());
if (canEmitExit) {
es.on('error', function (err) { harness._exitCode = 1 });
}
var ended = false;
stream.on('end', function () { ended = true });
if (conf.exit === false) return harness;
if (!canEmitExit || !canExit) return harness;
var _error;
process.on('uncaughtException', function (err) {
if (err && err.code === 'EPIPE' && err.errno === 'EPIPE'
&& err.syscall === 'write') return;
_error = err
throw err
})
process.on('exit', function (code) {
if (_error) {
return
}
if (!ended) {
var only = harness._results._only;
for (var i = 0; i < harness._tests.length; i++) {
var t = harness._tests[i];
if (only && t.name !== only) continue;
t._exit();
}
}
harness.close();
process.exit(code || harness._exitCode);
});
return harness;
}
exports.createHarness = createHarness;
exports.Test = Test;
exports.test = exports; // tap compat
exports.test.skip = Test.skip;
var exitInterval;
function createHarness (conf_) {
if (!conf_) conf_ = {};
var results = createResult();
if (conf_.autoclose !== false) {
results.once('done', function () { results.close() });
}
var test = function (name, conf, cb) {
var t = new Test(name, conf, cb);
test._tests.push(t);
(function inspectCode (st) {
st.on('test', function sub (st_) {
inspectCode(st_);
});
st.on('result', function (r) {
if (!r.ok) test._exitCode = 1
});
})(t);
results.push(t);
return t;
};
test._results = results;
test._tests = [];
test.createStream = function (opts) {
return results.createStream(opts);
};
var only = false;
test.only = function (name) {
if (only) throw new Error('there can only be one only test');
results.only(name);
only = true;
return test.apply(null, arguments);
};
test._exitCode = 0;
test.close = function () { results.close() };
return test;
}
}).call(this,require('_process'))
},{"./lib/default_stream":37,"./lib/results":38,"./lib/test":39,"_process":15,"defined":43,"through":47}],37:[function(require,module,exports){
(function (process){
var through = require('through');
var fs = require('fs');
module.exports = function () {
var line = '';
var stream = through(write, flush);
return stream;
function write (buf) {
for (var i = 0; i < buf.length; i++) {
var c = typeof buf === 'string'
? buf.charAt(i)
: String.fromCharCode(buf[i])
;
if (c === '\n') flush();
else line += c;
}
}
function flush () {
if (fs.writeSync && /^win/.test(process.platform)) {
try { fs.writeSync(1, line + '\n'); }
catch (e) { stream.emit('error', e) }
}
else {
try { console.log(line) }
catch (e) { stream.emit('error', e) }
}
line = '';
}
};
}).call(this,require('_process'))
},{"_process":15,"fs":6,"through":47}],38:[function(require,module,exports){
(function (process){
var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');
var through = require('through');
var resumer = require('resumer');
var inspect = require('object-inspect');
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
module.exports = Results;
inherits(Results, EventEmitter);
function Results () {
if (!(this instanceof Results)) return new Results;
this.count = 0;
this.fail = 0;
this.pass = 0;
this._stream = through();
this.tests = [];
}
Results.prototype.createStream = function (opts) {
if (!opts) opts = {};
var self = this;
var output, testId = 0;
if (opts.objectMode) {
output = through();
self.on('_push', function ontest (t, extra) {
if (!extra) extra = {};
var id = testId++;
t.once('prerun', function () {
var row = {
type: 'test',
name: t.name,
id: id
};
if (has(extra, 'parent')) {
row.parent = extra.parent;
}
output.queue(row);
});
t.on('test', function (st) {
ontest(st, { parent: id });
});
t.on('result', function (res) {
res.test = id;
res.type = 'assert';
output.queue(res);
});
t.on('end', function () {
output.queue({ type: 'end', test: id });
});
});
self.on('done', function () { output.queue(null) });
}
else {
output = resumer();
output.queue('TAP version 13\n');
self._stream.pipe(output);
}
nextTick(function next() {
var t;
while (t = getNextTest(self)) {
t.run();
if (!t.ended) return t.once('end', function(){ nextTick(next); });
}
self.emit('done');
});
return output;
};
Results.prototype.push = function (t) {
var self = this;
self.tests.push(t);
self._watch(t);
self.emit('_push', t);
};
Results.prototype.only = function (name) {
if (this._only) {
self.count ++;
self.fail ++;
write('not ok ' + self.count + ' already called .only()\n');
}
this._only = name;
};
Results.prototype._watch = function (t) {
var self = this;
var write = function (s) { self._stream.queue(s) };
t.once('prerun', function () {
write('# ' + t.name + '\n');
});
t.on('result', function (res) {
if (typeof res === 'string') {
write('# ' + res + '\n');
return;
}
write(encodeResult(res, self.count + 1));
self.count ++;
if (res.ok) self.pass ++
else self.fail ++
});
t.on('test', function (st) { self._watch(st) });
};
Results.prototype.close = function () {
var self = this;
if (self.closed) self._stream.emit('error', new Error('ALREADY CLOSED'));
self.closed = true;
var write = function (s) { self._stream.queue(s) };
write('\n1..' + self.count + '\n');
write('# tests ' + self.count + '\n');
write('# pass ' + self.pass + '\n');
if (self.fail) write('# fail ' + self.fail + '\n')
else write('\n# ok\n')
self._stream.queue(null);
};
function encodeResult (res, count) {
var output = '';
output += (res.ok ? 'ok ' : 'not ok ') + count;
output += res.name ? ' ' + res.name.toString().replace(/\s+/g, ' ') : '';
if (res.skip) output += ' # SKIP';
else if (res.todo) output += ' # TODO';
output += '\n';
if (res.ok) return output;
var outer = ' ';
var inner = outer + ' ';
output += outer + '---\n';
output += inner + 'operator: ' + res.operator + '\n';
if (has(res, 'expected') || has(res, 'actual')) {
var ex = inspect(res.expected);
var ac = inspect(res.actual);
if (Math.max(ex.length, ac.length) > 65) {
output += inner + 'expected:\n' + inner + ' ' + ex + '\n';
output += inner + 'actual:\n' + inner + ' ' + ac + '\n';
}
else {
output += inner + 'expected: ' + ex + '\n';
output += inner + 'actual: ' + ac + '\n';
}
}
if (res.at) {
output += inner + 'at: ' + res.at + '\n';
}
if (res.operator === 'error' && res.actual && res.actual.stack) {
var lines = String(res.actual.stack).split('\n');
output += inner + 'stack:\n';
output += inner + ' ' + lines[0] + '\n';
for (var i = 1; i < lines.length; i++) {
output += inner + lines[i] + '\n';
}
}
output += outer + '...\n';
return output;
}
function getNextTest (results) {
if (!results._only) {
return results.tests.shift();
}
do {
var t = results.tests.shift();
if (!t) continue;
if (results._only === t.name) {
return t;
}
} while (results.tests.length !== 0)
}
function has (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'))
},{"_process":15,"events":11,"inherits":44,"object-inspect":45,"resumer":46,"through":47}],39:[function(require,module,exports){
(function (process,__dirname){
var Stream = require('stream');
var deepEqual = require('deep-equal');
var defined = require('defined');
var path = require('path');
var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;
module.exports = Test;
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
inherits(Test, EventEmitter);
var getTestArgs = function (name_, opts_, cb_) {
var name = '(anonymous)';
var opts = {};
var cb;
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
var t = typeof arg;
if (t === 'string') {
name = arg;
}
else if (t === 'object') {
opts = arg || opts;
}
else if (t === 'function') {
cb = arg;
}
}
return { name: name, opts: opts, cb: cb };
};
function Test (name_, opts_, cb_) {
if (! (this instanceof Test)) {
return new Test(name_, opts_, cb_);
}
var args = getTestArgs(name_, opts_, cb_);
this.readable = true;
this.name = args.name || '(anonymous)';
this.assertCount = 0;
this.pendingCount = 0;
this._skip = args.opts.skip || false;
this._plan = undefined;
this._cb = args.cb;
this._progeny = [];
this._ok = true;
for (var prop in this) {
this[prop] = (function bind(self, val) {
if (typeof val === 'function') {
return function bound() {
return val.apply(self, arguments);
};
}
else return val;
})(this, this[prop]);
}
}
Test.prototype.run = function () {
if (!this._cb || this._skip) {
return this._end();
}
this.emit('prerun');
this._cb(this);
this.emit('run');
};
Test.prototype.test = function (name, opts, cb) {
var self = this;
var t = new Test(name, opts, cb);
this._progeny.push(t);
this.pendingCount++;
this.emit('test', t);
t.on('prerun', function () {
self.assertCount++;
})
if (!self._pendingAsserts()) {
nextTick(function () {
self._end();
});
}
nextTick(function() {
if (!self._plan && self.pendingCount == self._progeny.length) {
self._end();
}
});
};
Test.prototype.comment = function (msg) {
this.emit('result', msg.trim().replace(/^#\s*/, ''));
};
Test.prototype.plan = function (n) {
this._plan = n;
this.emit('plan', n);
};
Test.prototype.end = function (err) {
var self = this;
if (arguments.length >= 1) {
this.ifError(err);
}
if (this.calledEnd) {
this.fail('.end() called twice');
}
this.calledEnd = true;
this._end();
};
Test.prototype._end = function (err) {
var self = this;
if (this._progeny.length) {
var t = this._progeny.shift();
t.on('end', function () { self._end() });
t.run();
return;
}
if (!this.ended) this.emit('end');
var pendingAsserts = this._pendingAsserts();
if (!this._planError && this._plan !== undefined && pendingAsserts) {
this._planError = true;
this.fail('plan != count', {
expected : this._plan,
actual : this.assertCount
});
}
this.ended = true;
};
Test.prototype._exit = function () {
if (this._plan !== undefined &&
!this._planError && this.assertCount !== this._plan) {
this._planError = true;
this.fail('plan != count', {
expected : this._plan,
actual : this.assertCount,
exiting : true
});
}
else if (!this.ended) {
this.fail('test exited without ending', {
exiting: true
});
}
};
Test.prototype._pendingAsserts = function () {
if (this._plan === undefined) {
return 1;
}
else {
return this._plan - (this._progeny.length + this.assertCount);
}
};
Test.prototype._assert = function assert (ok, opts) {
var self = this;
var extra = opts.extra || {};
var res = {
id : self.assertCount ++,
ok : Boolean(ok),
skip : defined(extra.skip, opts.skip),
name : defined(extra.message, opts.message, '(unnamed assert)'),
operator : defined(extra.operator, opts.operator)
};
if (has(opts, 'actual') || has(extra, 'actual')) {
res.actual = defined(extra.actual, opts.actual);
}
if (has(opts, 'expected') || has(extra, 'expected')) {
res.expected = defined(extra.expected, opts.expected);
}
this._ok = Boolean(this._ok && ok);
if (!ok) {
res.error = defined(extra.error, opts.error, new Error(res.name));
}
var e = new Error('exception');
var err = (e.stack || '').split('\n');
var dir = path.dirname(__dirname) + '/';
for (var i = 0; i < err.length; i++) {
var m = /^\s*\bat\s+(.+)/.exec(err[i]);
if (!m) continue;
var s = m[1].split(/\s+/);
var filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[1]);
if (!filem) {
filem = /(\/[^:\s]+:(\d+)(?::(\d+))?)/.exec(s[3]);
if (!filem) continue;
}
if (filem[1].slice(0, dir.length) === dir) continue;
res.functionName = s[0];
res.file = filem[1];
res.line = Number(filem[2]);
if (filem[3]) res.column = filem[3];
res.at = m[1];
break;
}
self.emit('result', res);
var pendingAsserts = self._pendingAsserts();
if (!pendingAsserts) {
if (extra.exiting) {
self._end();
} else {
nextTick(function () {
self._end();
});
}
}
if (!self._planError && pendingAsserts < 0) {
self._planError = true;
self.fail('plan != count', {
expected : self._plan,
actual : self._plan - pendingAsserts
});
}
};
Test.prototype.fail = function (msg, extra) {
this._assert(false, {
message : msg,
operator : 'fail',
extra : extra
});
};
Test.prototype.pass = function (msg, extra) {
this._assert(true, {
message : msg,
operator : 'pass',
extra : extra
});
};
Test.prototype.skip = function (msg, extra) {
this._assert(true, {
message : msg,
operator : 'skip',
skip : true,
extra : extra
});
};
Test.prototype.ok
= Test.prototype['true']
= Test.prototype.assert
= function (value, msg, extra) {
this._assert(value, {
message : msg,
operator : 'ok',
expected : true,
actual : value,
extra : extra
});
};
Test.prototype.notOk
= Test.prototype['false']
= Test.prototype.notok
= function (value, msg, extra) {
this._assert(!value, {
message : msg,
operator : 'notOk',
expected : false,
actual : value,
extra : extra
});
};
Test.prototype.error
= Test.prototype.ifError
= Test.prototype.ifErr
= Test.prototype.iferror
= function (err, msg, extra) {
this._assert(!err, {
message : defined(msg, String(err)),
operator : 'error',
actual : err,
extra : extra
});
};
Test.prototype.equal
= Test.prototype.equals
= Test.prototype.isEqual
= Test.prototype.is
= Test.prototype.strictEqual
= Test.prototype.strictEquals
= function (a, b, msg, extra) {
this._assert(a === b, {
message : defined(msg, 'should be equal'),
operator : 'equal',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype.notEqual
= Test.prototype.notEquals
= Test.prototype.notStrictEqual
= Test.prototype.notStrictEquals
= Test.prototype.isNotEqual
= Test.prototype.isNot
= Test.prototype.not
= Test.prototype.doesNotEqual
= Test.prototype.isInequal
= function (a, b, msg, extra) {
this._assert(a !== b, {
message : defined(msg, 'should not be equal'),
operator : 'notEqual',
actual : a,
notExpected : b,
extra : extra
});
};
Test.prototype.deepEqual
= Test.prototype.deepEquals
= Test.prototype.isEquivalent
= Test.prototype.same
= function (a, b, msg, extra) {
this._assert(deepEqual(a, b, { strict: true }), {
message : defined(msg, 'should be equivalent'),
operator : 'deepEqual',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype.deepLooseEqual
= Test.prototype.looseEqual
= Test.prototype.looseEquals
= function (a, b, msg, extra) {
this._assert(deepEqual(a, b), {
message : defined(msg, 'should be equivalent'),
operator : 'deepLooseEqual',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype.notDeepEqual
= Test.prototype.notEquivalent
= Test.prototype.notDeeply
= Test.prototype.notSame
= Test.prototype.isNotDeepEqual
= Test.prototype.isNotDeeply
= Test.prototype.isNotEquivalent
= Test.prototype.isInequivalent
= function (a, b, msg, extra) {
this._assert(!deepEqual(a, b, { strict: true }), {
message : defined(msg, 'should not be equivalent'),
operator : 'notDeepEqual',
actual : a,
notExpected : b,
extra : extra
});
};
Test.prototype.notDeepLooseEqual
= Test.prototype.notLooseEqual
= Test.prototype.notLooseEquals
= function (a, b, msg, extra) {
this._assert(deepEqual(a, b), {
message : defined(msg, 'should be equivalent'),
operator : 'notDeepLooseEqual',
actual : a,
expected : b,
extra : extra
});
};
Test.prototype['throws'] = function (fn, expected, msg, extra) {
if (typeof expected === 'string') {
msg = expected;
expected = undefined;
}
var caught = undefined;
try {
fn();
}
catch (err) {
caught = { error : err };
var message = err.message;
delete err.message;
err.message = message;
}
var passed = caught;
if (expected instanceof RegExp) {
passed = expected.test(caught && caught.error);
expected = String(expected);
}
this._assert(passed, {
message : defined(msg, 'should throw'),
operator : 'throws',
actual : caught && caught.error,
expected : expected,
error: !passed && caught && caught.error,
extra : extra
});
};
Test.prototype.doesNotThrow = function (fn, expected, msg, extra) {
if (typeof expected === 'string') {
msg = expected;
expected = undefined;
}
var caught = undefined;
try {
fn();
}
catch (err) {
caught = { error : err };
}
this._assert(!caught, {
message : defined(msg, 'should not throw'),
operator : 'throws',
actual : caught && caught.error,
expected : expected,
error : caught && caught.error,
extra : extra
});
};
function has (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
Test.skip = function (name_, _opts, _cb) {
var args = getTestArgs.apply(null, arguments);
args.opts.skip = true;
return Test(args.name, args.opts, args.cb);
};
// vim: set softtabstop=4 shiftwidth=4:
}).call(this,require('_process'),"/node_modules/tape/lib")
},{"_process":15,"deep-equal":40,"defined":43,"events":11,"inherits":44,"path":14,"stream":27}],40:[function(require,module,exports){
var pSlice = Array.prototype.slice;
var objectKeys = require('./lib/keys.js');
var isArguments = require('./lib/is_arguments.js');
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return true;
}
},{"./lib/is_arguments.js":41,"./lib/keys.js":42}],41:[function(require,module,exports){
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
},{}],42:[function(require,module,exports){
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
},{}],43:[function(require,module,exports){
module.exports = function () {
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] !== undefined) return arguments[i];
}
};
},{}],44:[function(require,module,exports){
module.exports=require(12)
},{"/Users/darthapo/Projects/OpenSource/elucidata-ogre2/node_modules/browserify/node_modules/inherits/inherits_browser.js":12}],45:[function(require,module,exports){
module.exports = function inspect_ (obj, opts, depth, seen) {
if (!opts) opts = {};
var maxDepth = opts.depth === undefined ? 5 : opts.depth;
if (depth === undefined) depth = 0;
if (depth > maxDepth && maxDepth > 0) return '...';
if (seen === undefined) seen = [];
else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect (value, from) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'string') {
return inspectString(obj);
}
else if (typeof obj === 'function') {
var name = nameOf(obj);
return '[Function' + (name ? ': ' + name : '') + ']';
}
else if (obj === null) {
return 'null';
}
else if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"';
}
s += '>';
if (obj.childNodes && obj.childNodes.length) s += '...';
s += '</' + String(obj.tagName).toLowerCase() + '>';
return s;
}
else if (isArray(obj)) {
if (obj.length === 0) return '[]';
var xs = Array(obj.length);
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
return '[ ' + xs.join(', ') + ' ]';
}
else if (typeof obj === 'object' && typeof obj.inspect === 'function') {
return obj.inspect();
}
else if (typeof obj === 'object' && !isDate(obj) && !isRegExp(obj)) {
var xs = [], keys = [];
for (var key in obj) {
if (has(obj, key)) keys.push(key);
}
keys.sort();
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (/[^\w$]/.test(key)) {
xs.push(inspect(key) + ': ' + inspect(obj[key], obj));
}
else xs.push(key + ': ' + inspect(obj[key], obj));
}
if (xs.length === 0) return '{}';
return '{ ' + xs.join(', ') + ' }';
}
else return String(obj);
};
function quote (s) {
return String(s).replace(/"/g, '"');
}
function isArray (obj) {
return {}.toString.call(obj) === '[object Array]';
}
function isDate (obj) {
return {}.toString.call(obj) === '[object Date]';
}
function isRegExp (obj) {
return {}.toString.call(obj) === '[object RegExp]';
}
function has (obj, key) {
if (!{}.hasOwnProperty) return key in obj;
return {}.hasOwnProperty.call(obj, key);
}
function nameOf (f) {
if (f.name) return f.name;
var m = f.toString().match(/^function\s*([\w$]+)/);
if (m) return m[1];
}
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
function isElement (x) {
if (!x || typeof x !== 'object') return false;
if (typeof HTMLElement !== 'undefined') {
return x instanceof HTMLElement;
}
else return typeof x.nodeName === 'string'
&& typeof x.getAttribute === 'function'
;
}
function inspectString (str) {
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return "'" + s + "'";
function lowbyte (c) {
var n = c.charCodeAt(0);
var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n];
if (x) return '\\' + x;
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}
}
},{}],46:[function(require,module,exports){
(function (process){
var through = require('through');
var nextTick = typeof setImmediate !== 'undefined'
? setImmediate
: process.nextTick
;
module.exports = function (write, end) {
var tr = through(write, end);
tr.pause();
var resume = tr.resume;
var pause = tr.pause;
var paused = false;
tr.pause = function () {
paused = true;
return pause.apply(this, arguments);
};
tr.resume = function () {
paused = false;
return resume.apply(this, arguments);
};
nextTick(function () {
if (!paused) tr.resume();
});
return tr;
};
}).call(this,require('_process'))
},{"_process":15,"through":47}],47:[function(require,module,exports){
(function (process){
var Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end, opts) {
write = write || function (data) { this.queue(data) }
end = end || function () { this.queue(null) }
var ended = false, destroyed = false, buffer = [], _ended = false
var stream = new Stream()
stream.readable = stream.writable = true
stream.paused = false
// stream.autoPause = !(opts && opts.autoPause === false)
stream.autoDestroy = !(opts && opts.autoDestroy === false)
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
function drain() {
while(buffer.length && !stream.paused) {
var data = buffer.shift()
if(null === data)
return stream.emit('end')
else
stream.emit('data', data)
}
}
stream.queue = stream.push = function (data) {
// console.error(ended)
if(_ended) return stream
if(data == null) _ended = true
buffer.push(data)
drain()
return stream
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
//this is only a problem if end is not emitted synchronously.
//a nicer way to do this is to make sure this is the last listener for 'end'
stream.on('end', function () {
stream.readable = false
if(!stream.writable && stream.autoDestroy)
process.nextTick(function () {
stream.destroy()
})
})
function _end () {
stream.writable = false
end.call(stream)
if(!stream.readable && stream.autoDestroy)
stream.destroy()
}
stream.end = function (data) {
if(ended) return
ended = true
if(arguments.length) stream.write(data)
_end() // will emit or queue
return stream
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
buffer.length = 0
stream.writable = stream.readable = false
stream.emit('close')
return stream
}
stream.pause = function () {
if(stream.paused) return
stream.paused = true
return stream
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
stream.emit('resume')
}
drain()
//may have become paused again,
//as drain emits 'data'.
if(!stream.paused)
stream.emit('drain')
return stream
}
return stream
}
}).call(this,require('_process'))
},{"_process":15,"stream":27}],48:[function(require,module,exports){
var type= require( 'elucidata-type')
function test_object( ds, t) {
ds.set('misc', 'ITEM')
t.equal( ds.get('misc'), 'ITEM')
ds.merge('left', { name:'MID'})
t.equal( ds.get('left.name'), 'MID')
t.end()
}
function test_array( ds, t) {
// ds.set( 'list', [])
ds.push('list', 'hello')
ds.push('list', 1)
t.equal( ds.get('list.length'), 2)
ds.splice('list', 0, 1)
t.equal( ds.get('list.length'), 1)
ds.unshift('list', 'new')
t.equal( ds.get('list.length'), 2)
t.equal( ds.get('list.0'), 'new')
t.end()
}
function test_query( ds, t) {
t.plan(15)
ds.push('list', ['a','b','c','d'])
t.equal( ds.get('list.length'), 4)
ds.each( 'list', function( val){
t.ok( val)
})
ds.push('list2', [1,2,3,4])
t.equal( ds.get('list2.length'), 4)
var r= ds.map( 'list2', function( val){
t.ok( val)
return val + 1
})
t.deepLooseEqual(r, [2,3,4,5])
t.deepLooseEqual( ds.get('list2'), [1,2,3,4])
var f= ds.filter( 'list2', function(val){
return val > 2
})
t.deepLooseEqual(f, [3,4])
var ff= ds.find( 'list2', function(val){
return val > 2
})
t.equal(ff, 3)
var i= ds.indexOf( 'list', 'b')
t.equal(i, 1)
// t.end()
}
function test_other( ds, t) {
if( ds.source) {
// Cursor
ds.set('value')
t.equal( ds.get(), 'value', 'set( string) on cursor')
var value= ['item']
ds.set(value)
t.equal( ds.get(), value, 'set( array) on cursor')
value= {}
ds.set(value)
t.equal( ds.get(), value, 'set( object) on cursor')
value= { hello:'hello'}
ds.merge(value)
t.deepLooseEqual( ds.get(), value, 'merge( object) on cursor')
value= { bob:'Robert'}
ds.merge(value)
t.deepLooseEqual( ds.get(), { hello:'hello', bob:'Robert'}, 'merge( object) on cursor')
value= 10
ds.set(value)
t.equal( ds.get(), value, 'set( number) on cursor')
value= true
ds.set(value)
t.equal( ds.get(), value, 'set( boolean) on cursor')
value= null
ds.set(value)
t.equal( ds.get(), value, 'set( null) on cursor')
value= []
ds.set(value)
t.equal( ds.get(), value, 'set( empty_array) on cursor')
value= 'item'
ds.push( value)
t.equal( type( ds.get()), 'array', 'push( string) on cursor')
t.deepLooseEqual( ds.get(), ['item'])
t.equal( ds.get('length'), 1)
value= 'item2'
ds.unshift( value)
t.deepLooseEqual( ds.get(), ['item2', 'item'])
t.equal( ds.get('length'), 2)
var r= ds.map(function( val){
t.ok( val)
return val + 'X'
})
t.deepLooseEqual(r, ['item2X', 'itemX'])
r= ds.filter(function( val){
t.ok( val)
return val === 'item'
})
t.deepLooseEqual(r, ['item'])
r= ds.find(function( val){
t.ok( val)
return val === 'item'
})
t.deepLooseEqual(r, 'item')
r= ds.indexOf('item')
t.equal(r, 1)
}
else {
t.throws(function(){
ds.set('value')
}, /Invalid set/,
"Empty .set() call not allowed on root Ogre dataset.")
}
t.end()
}
function test_array_keys( ds, t) {
t.equal( ds.get(['left']), ds.get('left'), 'get() with array key')
ds.set(['left', 'name'], "LEFT")
t.equal( ds.get(['left', 'name']), "LEFT", 'set() with array key')
t.equal( ds.get('left.name'), "LEFT", '... part deux')
ds.merge(['left'], { other:"OTHER"})
t.equal( ds.get(['left', 'other']), "OTHER", 'merge() with array key')
t.equal( ds.get('left.other'), "OTHER", '... part deux')
ds.push(['right', 'list'], 'A')
t.equal( ds.get(['right', 'list', '0']), "A", 'push() with array key')
t.equal( ds.get('right.list.0'), ds.get(['right', 'list', '0']), '... part deux')
ds.unshift(['right', 'list'], 'B')
t.equal( ds.get(['right', 'list', '0']), "B", 'unshift() with array key')
t.equal( ds.get('right.list.0'), ds.get(['right', 'list', '0']), '... part deux')
t.end()
}
module.exports= {
test_object: test_object,
test_array: test_array,
test_query: test_query,
test_other: test_other,
test_array_keys: test_array_keys
}
},{"elucidata-type":29}],49:[function(require,module,exports){
var Ogre= require('../'), type= require('elucidata-type'),
// test= require('prova')
test= require('tape'),
_= require( './_helpers')
test( 'Basic tests', function( t ){
t.notEqual( Ogre, null, "exported value is not null" )
t.equal( typeof Ogre, 'function', "exported value is a function" )
t.equal( typeof Ogre.version, 'string', "exported .version string" )
t.end()
})
test( '.get() returns correct values', function(t){
var src= { name:'Ogre', info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
t.equal( src, ds.get(), "returned value is the same object.")
t.equal( ds.get('info.version'), 2, 'simple key path traversal')
t.equal( ds.get('info.more.extra.value'), 'STUFF', 'deeply nested key path traversal')
t.equal( ds.get('info.more.extra'), src.info.more.extra, 'object fetched is same as source, if unchanged')
t.end()
})
test( '.get() returns correct values for array keys too', function(t){
var src= { name:'Ogre', info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
t.equal( src, ds.get([]), "returned value is the same object.")
t.equal( ds.get(['info','version']), 2, 'simple key path traversal')
t.equal( ds.get(['info','more','extra','value']), 'STUFF', 'deeply nested key path traversal')
t.equal( ds.get(['info','more','extra']), src.info.more.extra, 'object fetched is same as source, if unchanged')
t.end()
})
test( '.set() only modifies changed objects', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
ds.set('info.more.extra.value', 'New')
t.notEqual( ds.get(), src, 'returned value is a new object.')
t.equal( ds.get('peer'), src.peer, 'unchanged branch is still the same object')
t.notEqual( ds.get('info.more.extra'), src.info.more.extra, 'changed branch is new object')
t.end()
})
test( '.set() only modifies changed objects using array keys too', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
ds.set(['info','more','extra','value'], 'New')
t.notEqual( ds.get(), src, 'returned value is a new object.')
t.equal( ds.get(['peer']), src.peer, 'unchanged branch is still the same object')
t.notEqual( ds.get(['info','more','extra']), src.info.more.extra, 'changed branch is new object')
t.end()
})
test( '.onChange() events are fired', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
t.plan( 1 )
ds.onChange(function(keys){
t.deepEqual( keys, ['info.more.extra.value'], "event fired with correct changed key array")
})
ds.set('info.more.extra.value', 'New')
})
test( '.onChange() events are fired in a batch fashion', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
t.plan( 1 )
ds.onChange(function(keys){
t.deepEqual( keys, ['info.more.extra.value', 'peer.name'], "event fired with correct changed key array")
})
ds.set('info.more.extra.value', 'New')
ds.set('peer.name', 'New')
})
test( '.onChange() events are fired individually if configured so', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src, { batchChanges:false })
t.plan( 3 )
ds.onChange(function(keys){
t.equal(keys.length, 1, "onChange triggered with single changed key")
// t.pass("single onChange triggered")
// t.deepEqual( keys, ['info.more.extra.value', 'peer.name'], "event fired with correct changed key array")
})
ds.set('info.more.extra.value', 'New')
ds.set('peer.name', 'New')
ds.set('info.more.extra.value', 'Really New')
})
test('.offChange() should unsubscribe handler from events', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src),
callback= function(keys) {
t.deepEqual( keys, ['info.more.extra.value', 'peer.name'], "event fired with correct changed key array")
}
t.plan( 2 )
ds.onChange( callback )
ds.set('info.more.extra.value', 'New')
ds.set('peer.name', 'New')
// Since we're batching calls, we can't unsubscribe on this tick.
setTimeout(function(){
ds.offChange( callback )
ds.set('peer.name', "Really New!")
t.pass('unsubscribed')
},1)
})
test( 'strict mode fails to create missing key paths', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
t.plan( 1 )
t.throws(function(){
ds.set('made.up.non.existant.path', 'YES')
})
})
test( 'non-strict mode creates missing key paths', function(t){
var src= { name:'Ogre', peer:{ name:'Uh huh' }, info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src, { strict: false })
t.plan(8)
t.doesNotThrow(function(){
ds.set('made.up.non.existant.path', 'YES')
t.equal( ds.get('made.up.non.existant.path'), 'YES', "new value is set")
})
ds.set('test.set', 'VALUE')
ds.set('test.set2', { value:'VALUE' })
ds.merge('test.merge', { value:'VALUE' })
ds.push('test.push', 'VALUE')
ds.unshift('test.unshift', "VALUE")
ds.splice('test.splice', 1, 0, "VALUE")
t.equal( type(ds.get('test.set')), 'string', 'result of set is string')
t.equal( type(ds.get('test.set2')), 'object', 'result of set is object')
t.equal( type(ds.get('test.merge')), 'object', 'result of merge is object')
t.equal( type(ds.get('test.push')), 'array', 'result of push is array')
t.equal( type(ds.get('test.unshift')), 'array', 'result of unshift is array')
t.equal( type(ds.get('test.splice')), 'array', 'result of splice is array')
})
test( 'test object-like mutators', function( t){
var src= new Ogre({ left:{}, right:{} }, { strict:false })
_.test_object( src, t)
})
test( 'test array-like mutators', function( t){
var src= new Ogre({ left:{}, right:{} }, { strict:false })
_.test_array( src, t)
})
test( 'test query methods', function( t){
var src= new Ogre({ left:{}, right:{} }, { strict:false })
_.test_query( src, t)
})
test( 'test other methods', function( t){
var src= new Ogre({ left:{}, right:{} }, { strict:false })
_.test_other( src, t)
})
test( 'test array key methods', function( t){
var src= new Ogre({ left:{}, right:{} }, { strict:false })
_.test_array_keys( src, t)
})
},{"../":1,"./_helpers":48,"elucidata-type":29,"tape":36}],50:[function(require,module,exports){
var Ogre= require('../'),
Cursor= require('../lib/cursor'),
type= require('elucidata-type'),
// test= require('prova')
test= require('tape'),
_= require( './_helpers')
function testx(){}
test( 'Basic cursor tests', function( t ){
t.notEqual( Ogre, null, "exported value is not null" )
t.equal( typeof Ogre, 'function', "exported value is a function" )
test( '.scopeTo( path)', function(t){
var src= { name:'Ogre', info:{ version:2, more:{ extra:{ value:'STUFF' } }} },
ds= new Ogre(src)
t.ok( ds.scopeTo, "exists" )
t.end()
})
t.end()
})
test( 'Sub-tree modification via Cursor.set()', function( t){
var src= new Ogre({ left:{}, right:{}, middle:{} }, { strict:false }),
left= src.scopeTo( 'left'),
right= src.scopeTo( 'right')
t.ok( left, 'Left cursor created.')
t.ok( right, 'Right cursor created.')
t.ok( left.get(), 'Left.get() returns non-empty object.')
t.ok( right.get(), 'Right.get() returns non-empty object.')
src.set( 'middle.name', 'Something')
t.equal( left.get(), src.get( 'left'), 'Sub-tree unaffected by unrelated change.')
t.equal( right.get(), src.get( 'right'), 'Sub-tree unaffected by unrelated change.')
var left_value= 'LEFT VALUE'
left.set( left_value)
t.equal( src.get( 'left'), left_value, 'String value. Sub-tree correctly modifies root tree.')
left_value= 42
left.set( left_value)
t.equal( src.get( 'left'), left_value, 'Number value. Sub-tree correctly modifies root tree.')
left_value= null
left.set( left_value)
t.equal( src.get( 'left'), left_value, 'Null value. Sub-tree correctly modifies root tree.')
var right_value= { label:'RIGHT VALUE'}
right.set( right_value)
t.equal( src.get( 'right'), right_value, 'Object value. Sub-tree correctly modifies root tree.')
right_value= ''
right.set( right_value)
t.equal( src.get( 'right'), right_value, 'Empty string value. Sub-tree correctly modifies root tree.')
right_value= ['left', 'value']
right.set( right_value)
t.equal( src.get( 'right'), right_value, 'Array value. Sub-tree correctly modifies root tree.')
right.push(['new'])
t.equal( src.get( 'right.length'), 3, 'Array value. Sub-tree correctly modifies root tree.')
right.push({})
t.ok( src.get( 'right'), 'Empty object. Sub-tree correctly modifies root tree.')
right.set({})
left.set({})
left_value= 'LEFT VALUE'
left.set( 'child', left_value)
t.equal( src.get( 'left.child'), left_value, 'Pathed String value. Sub-tree correctly modifies root tree.')
left_value= 42
left.set( 'child', left_value)
t.equal( src.get( 'left.child'), left_value, 'Pathed Number value. Sub-tree correctly modifies root tree.')
left_value= null
left.set( 'child', left_value)
t.equal( src.get( 'left.child'), left_value, 'Pathed Null value. Sub-tree correctly modifies root tree.')
left.set({})
left_value= 'Hello'
left.set( 'child.much.deeper', left_value)
t.equal( src.get( 'left.child.much.deeper'), left_value, 'Deeply pathed string value. Sub-tree correctly modifies root tree.')
right_value= { label:'RIGHT VALUE'}
right.set( 'child', right_value)
t.equal( src.get( 'right.child'), right_value, 'Pathed Object value. Sub-tree correctly modifies root tree.')
right_value= ''
right.set( 'child', right_value)
t.equal( src.get( 'right.child'), right_value, 'Pathed Empty string value. Sub-tree correctly modifies root tree.')
right_value= ['left', 'value']
right.set( 'child', right_value)
t.equal( src.get( 'right.child'), right_value, 'Pathed Array value. Sub-tree correctly modifies root tree.')
right.push('child', ['new'])
t.equal( src.get( 'right.child.length'), 3, 'Pathed Array value. Sub-tree correctly modifies root tree.')
t.end()
})
test( 'Sub-tree events (extracted from app)', function ( t){
t.plan( 14 )
var src= new Ogre({
peer1: {
name: 'p1'
},
peer2: {
name: 'p2'
}
}, { strict:false}),
_root_count= 0,
_p1_count= 0,
_p2_count= 0
function root_onChange( keys){
// console.log('orge.onChange', keys)
_root_count += 1
t.ok( keys, 'root onChange')
}
src.onChange( root_onChange)
var p1= src.scopeTo( 'peer1'),
p2= src.scopeTo( 'peer2'),
p22= src.scopeTo( 'peer2')
function peer1_onChange( keys){
_p1_count += 1
t.ok( keys, 'peer1 onChange')
// console.log( 'peer1.onChange', keys)
}
p1.onChange( peer1_onChange)
function peer2_onChange( keys){
_p2_count += 1
t.ok( keys, 'peer2 onChange')
// console.log( 'peer2.onChange', keys)
}
p2.onChange( peer2_onChange)
// p22.onChange(function(){
// console.log( ">>>>>>>>>>>> Second call")
// console.log( Cursor.listenerInfo( true))
// })
src.set( 'peer1.name', 'TEST')
src.set( 'peer2.name', 'SHIT')
setTimeout(function(){
src.set('other.stuff', 'JUNK')
}, 100)
setTimeout(function(){
src.set('peer1.has.stuff', 'JUNK')
}, 200)
setTimeout(function(){
src.set('peer2.has.more.stuff', 'JUNK')
}, 300)
setTimeout(function(){
var expected= { totalEventHandlers: 2, totalKeyWatches: 2, totalSources: 1 }
t.deepLooseEqual( Cursor.listenerInfo(), expected)
t.equal( src._emitter.listeners('change').length, 2, 'only two listeners on the source object' )
// console.log( src._emitter.listeners('change') )
// console.log( src._emitter.listeners('change', true) )
src.offChange( root_onChange)
// console.log( src._emitter.listeners('change') )
// console.log( src._emitter.listeners('change', true) )
t.equal( src._emitter.listeners('change').length, 1, 'now only one' )
t.deepLooseEqual( Cursor.listenerInfo(), expected)
p1.offChange( peer1_onChange)
expected= { totalEventHandlers: 1, totalKeyWatches: 1, totalSources: 1 }
t.deepLooseEqual( Cursor.listenerInfo(), expected)
p2.offChange( peer2_onChange)
expected= { totalEventHandlers: 0, totalKeyWatches: 0, totalSources: 0 }
t.deepLooseEqual( Cursor.listenerInfo(), expected)
// console.log( src._emitter.listeners('change') )
// console.log( src._emitter.listeners('change', true) )
}, 400)
})
test( 'test cursor change events', function( t){
var src= new Ogre({
peer1: {
name: 'p1'
},
peer2: {
name: 'p2'
}
}, { strict:false, batchChanges:false}),
peer1= src.scopeTo( 'peer1'),
peer2= src.scopeTo( 'peer2')
function changed(target, keys) {
t.ok( keys, target+ ' keys changed: '+ keys.join(', '))
// console.log('> changed', key)
}
t.plan( 5)
src.onChange( changed.bind(this, 'root'))
peer1.onChange( changed.bind(this, 'peer1'))
peer2.onChange( changed.bind(this, 'peer2'))
// console.log(">> src.set('unrelated', 'value')")
src.set('unrelated', 'value') // 1
// console.log(">> peer1.set('name', 'updated')")
peer1.set('name', 'updated') // 2
// console.log(">> peer2.set('name', 'updated')")
peer2.set('name', 'updated') // 2
})
test( 'test object-like mutators', function( t){
var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
cursor= src.scopeTo( 'child')
_.test_object( cursor, t)
})
test( 'test array-like mutators', function( t){
var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
cursor= src.scopeTo( 'child')
_.test_array( cursor, t)
})
test( 'test query methods', function( t){
var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
cursor= src.scopeTo( 'child')
_.test_query( cursor, t)
})
test( 'test other methods', function( t){
var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
cursor= src.scopeTo( 'child')
_.test_other( cursor, t)
})
test( 'test array key methods', function( t){
var src= new Ogre({ child:{ left:{}, right:{} } }, { strict:false }),
cursor= src.scopeTo( 'child')
_.test_array_keys( cursor, t)
})
test( 'nested cursor change events', function( t){
var src= new Ogre({ }, { strict:false, batchChanges:false }),
forms= src.scopeTo( 'forms'),
email= forms.scopeTo( 'email'),
state= email.scopeTo( 'data'),
status= email.scopeTo( 'status')
t.plan( 5)
status.onChange(function( keys){
t.ok(true, keys +': '+ status.get(), "Status change event fired")
})
status.set('loading')
email.set('status', 'ready')
forms.set('email.status', 'uno_momento')
status.set('done')
t.deepLooseEqual( src.get(), { forms:{ email:{ status:'done'}}}, "Final data is in correct shape.")
})
test( 'nested cursor change events, batched', function( t){
var src= new Ogre({ }, { strict:false, batchChanges:true }),
forms= src.scopeTo( 'forms'),
email= forms.scopeTo( 'email'),
state= email.scopeTo( 'data'),
status= email.scopeTo( 'status')
t.plan( 2)
status.onChange(function( keys){
t.ok(true, keys +': '+ status.get(), "Status change event fired")
})
// status.set('loading')
email.set('status', 'ready')
forms.set('email.status', 'start')
forms.set('email.status', 'middle')
forms.set('email.status', 'uno_momento')
// status.set('done')
t.deepLooseEqual( src.get(), { forms:{ email:{ status:'uno_momento'}}}, "Final data is in correct shape.")
})
test( 'nested cursor change events, batched take two', function( t){
var src= new Ogre({ }, { strict:false, batchChanges:true }),
forms= src.scopeTo( 'forms'),
email= forms.scopeTo( 'email'),
state= email.scopeTo( 'data'),
status= email.scopeTo( 'status')
t.plan( 2)
forms.onChange(function( keys){
t.ok(true, keys +': '+ status.get(), "Status change event fired")
})
// status.set('loading')
email.set('status', 'ready')
forms.set('email.status', 'start')
forms.set('email.status', 'middle')
forms.set('email.status', 'uno_momento')
// status.set('done')
t.deepLooseEqual( src.get(), { forms:{ email:{ status:'uno_momento'}}}, "Final data is in correct shape.")
})
},{"../":1,"../lib/cursor":2,"./_helpers":48,"elucidata-type":29,"tape":36}]},{},[48,49,50]);
|
src/Survey/Default/Location.js | NERC-CEH/irecord-app | import React from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import { IonPage } from '@ionic/react';
import Log from 'helpers/log';
import Header from 'Components/Location/Header';
import Main from 'Components/Location/Main';
import {
onManualGridrefChange,
onLocationNameChange,
onGPSClick,
} from 'Components/Location/utils';
@observer
class Container extends React.Component {
static propTypes = {
savedSamples: PropTypes.array.isRequired,
match: PropTypes.object,
history: PropTypes.object,
appModel: PropTypes.object.isRequired,
};
constructor(props) {
super(props);
this.state = {
sample: this.props.savedSamples.find(
({ cid }) => cid === this.props.match.params.id
),
};
this.onManualGridrefChange = onManualGridrefChange.bind(this);
this.onGPSClick = onGPSClick.bind(this);
}
onLocationNameChange = (...args) => {
const { appModel } = this.props;
onLocationNameChange.apply(this, args);
const { location } = this.state.sample.attrs;
if (!location.latitude) {
return;
}
appModel.setLocation(location);
};
updateLocationLock = (location, locationWasLocked) => {
const { appModel } = this.props;
const currentLock = appModel.getAttrLock('smp:location');
// location
if (location.source !== 'gps' && location.latitude) {
const clonedLocation = JSON.parse(JSON.stringify(location));
// remove location name as it is locked separately
delete clonedLocation.name;
// we can lock location and name on their own
// don't lock GPS though, because it varies more than a map or gridref
if (currentLock && (currentLock === true || locationWasLocked)) {
// update locked value if attr is locked
// check if previously the value was locked and we are updating
Log('Updating lock.');
appModel.setAttrLock('smp:location', clonedLocation);
}
} else if (currentLock === true) {
// reset if no location or location name selected but locked is clicked
appModel.unsetAttrLock('smp', 'location');
}
};
onPastLocationsClick = () =>
this.props.history.push(
`/survey/default/${this.state.sample.cid}/edit/location/past`
);
onLocationLockClick = () => {
Log('Location:Controller: executing onLocationLockClick.');
const { appModel } = this.props;
const { sample } = this.state;
const isLocked = appModel.getAttrLock('smp', 'location');
if (isLocked) {
appModel.unsetAttrLock('smp', 'location');
return;
}
const { name, ...location } = sample.attrs.location;
if (!location) {
return;
}
appModel.setAttrLock('smp', 'location', location);
};
onNameLockClick = () => {
Log('Location:Controller: executing onNameLockClick.');
const { appModel } = this.props;
const { sample } = this.state;
const isLocked = appModel.getAttrLock('smp', 'locationName');
if (isLocked) {
appModel.unsetAttrLock('smp', 'locationName');
return;
}
const locationName = sample.attrs.location.name;
if (!locationName) {
return;
}
appModel.setAttrLock('smp', 'locationName', locationName);
};
setLocation = async loc => {
const { appModel } = this.props;
const { sample } = this.state;
if (typeof loc !== 'object') {
// jQuery event object bug fix
// todo clean up if not needed anymore
Log('Location:Controller:setLocation: loc is not an object.', 'e');
return Promise.reject(new Error('Invalid location'));
}
// // check if we need custom location setting functionality
// if (locationSetFunc) {
// return locationSetFunc(sample, loc);
// }
const oldLocation = sample.attrs.location || {};
const location = { ...loc, ...{ name: oldLocation.name } };
// we don't need the GPS running and overwriting the selected location
if (sample.isGPSRunning()) {
sample.stopGPS();
}
if (location.latitude) {
await appModel.setLocation(location);
}
sample.attrs.location = location;
return sample.save().catch(error => {
Log(error, 'e');
// radio.trigger('app:dialog:error', error);
});
};
render() {
const { appModel } = this.props;
const { sample } = this.state;
const location = sample.attrs.location || {};
return (
<IonPage id="survey-default-edit-location">
<Header
location={location}
sample={sample}
appModel={appModel}
onNameLockClick={this.onNameLockClick}
onLocationLockClick={this.onLocationLockClick}
onManualGridrefChange={this.onManualGridrefChange}
onLocationNameChange={this.onLocationNameChange}
/>
<Main
onPastLocationsClick={this.onPastLocationsClick}
location={location}
sample={sample}
appModel={appModel}
onGPSClick={this.onGPSClick}
setLocation={this.setLocation}
/>
</IonPage>
);
}
}
export default Container;
|
fixtures/nesting/src/legacy/Greeting.js | cpojer/react | import React from 'react';
import {Component} from 'react';
import {findDOMNode} from 'react-dom';
import {Link} from 'react-router-dom';
import {connect} from 'react-redux';
import {store} from '../store';
import ThemeContext from './shared/ThemeContext';
import Clock from './shared/Clock';
store.subscribe(() => {
console.log('Counter:', store.getState());
});
class AboutSection extends Component {
componentDidMount() {
// The modern app is wrapped in StrictMode,
// but the legacy bits can still use old APIs.
findDOMNode(this);
}
render() {
return (
<ThemeContext.Consumer>
{theme => (
<div style={{border: '1px dashed black', padding: 20}}>
<h3>src/legacy/Greeting.js</h3>
<h4 style={{color: theme}}>
This component is rendered by the nested React ({React.version}).
</h4>
<Clock />
<p>
Counter: {this.props.counter}{' '}
<button onClick={() => this.props.dispatch({type: 'increment'})}>
+
</button>
</p>
<b>
<Link to="/">Go to Home</Link>
</b>
</div>
)}
</ThemeContext.Consumer>
);
}
}
function mapStateToProps(state) {
return {counter: state};
}
export default connect(mapStateToProps)(AboutSection);
|
src/svg-icons/av/subtitles.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvSubtitles = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM4 12h4v2H4v-2zm10 6H4v-2h10v2zm6 0h-4v-2h4v2zm0-4H10v-2h10v2z"/>
</SvgIcon>
);
AvSubtitles = pure(AvSubtitles);
AvSubtitles.displayName = 'AvSubtitles';
export default AvSubtitles;
|
packages/core/src/icons/components/Tickets.js | iCHEF/gypcrete | import React from 'react';
export default function SvgTickets(props) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="1em"
height="1em"
viewBox="0 0 32 32"
{...props}
>
<path
data-name="\u9577\u65B9\u5F62 21 \u306E\u30B3\u30D4\u30FC 6"
d="M21 23v3H8V9h2V6h13v17h-2zm-11 1h1v-1h1v1h1v-1h1v1h1v-1h1v1h1v-1h1v1h1V11h-9v13zM21 8h-9v2h8v11h1V8zm-3 6h-7v-1h7v1zm0 2h-7v-1h7v1zm-1 2h-6v-1h6v1z"
fillRule="evenodd"
/>
</svg>
);
}
|
src/views/components/ScaleCard.js | physiii/open-automation | import React from 'react';
import PropTypes from 'prop-types';
import Button from './Button.js';
import {connect} from 'react-redux';
import {compose} from 'redux';
import {withRouter} from 'react-router-dom';
import {doServiceAction} from '../../state/ducks/services-list/operations.js';
import ServiceCardBase from './ServiceCardBase.js';
import './ScaleCard.css';
export class ScaleCard extends React.Component {
constructor (props) {
super(props);
this.state = {
is_changing: false
};
}
onCardClick () {
this.setLevel(this.props.service.state.get('light_level') > 0 ? 0 : 1);
}
getPercentage1 (value) {
return Math.round(value) / 100;
}
getPercentage100 (value) {
return Math.round(value * 100);
}
setLevel (value) {
if (!this.props.service.state.get('connected')) {
return;
}
this.props.doAction(this.props.service.id, {
property: 'light_level',
value
});
}
minTwoDigits (number) {
return (number < 10 ? '0' : '') + number;
}
render () {
const isConnected = this.props.service.state.get('connected');
return (
<ServiceCardBase
name={this.props.service.settings.get('name') || 'Scale'}
status={this.props.service.state.get('connected')
? Math.trunc(this.props.service.state.get('cycletime') / 604800) + 'w ' +
Math.trunc((this.props.service.state.get('cycletime') % 604800) / 86400) + 'd ' +
this.minTwoDigits(Math.trunc((this.props.service.state.get('cycletime') % 86400) / 3600)) + ':' +
this.minTwoDigits(Math.trunc((this.props.service.state.get('cycletime') % 3600) / 60)) + ':' +
this.minTwoDigits(this.props.service.state.get('cycletime') % 60)
: 'Unknown'}
isConnected={isConnected}
// secondaryAction={<Button>{this.props.service.settings.get('name') || 'Bill Acceptor'} Log</Button>}
secondaryAction={<Button to={`${this.props.match.url}/device-log/${this.props.service.id}`}>Device Log</Button>}
onCardClick={this.onCardClick.bind(this)}
{...this.props}>
<div styleName="container">
<section>
<span styleName="sensorTitle">
{this.props.service.state.get('weight') ? this.props.service.state.get('weight').toFixed(1) : '0'} lbs
</span>
<br />
</section>
</div>
</ServiceCardBase>
);
}
}
ScaleCard.propTypes = {
match: PropTypes.object,
service: PropTypes.object,
doAction: PropTypes.func
};
const mergeProps = (stateProps, {dispatch}, ownProps) => ({
...ownProps,
...stateProps,
doAction: (serviceId, action) => dispatch(doServiceAction(serviceId, action))
});
// export default connect(null, null, mergeProps)(ScaleCard);
export default compose(
connect(null, null, mergeProps),
withRouter
)(ScaleCard);
|
public/assets/js/node_modules/react-select/examples/src/components/ValuesAsNumbersField.js | ngocson8b/6jar | import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var ValuesAsNumbersField = React.createClass({
displayName: 'ValuesAsNumbersField',
propTypes: {
label: React.PropTypes.string
},
getInitialState () {
return {
options: [
{ value: 10, label: 'Ten' },
{ value: 11, label: 'Eleven' },
{ value: 12, label: 'Twelve' },
{ value: 23, label: 'Twenty-three' },
{ value: 24, label: 'Twenty-four' }
],
matchPos: 'any',
matchValue: true,
matchLabel: true,
value: null,
multi: false
};
},
onChangeMatchStart(event) {
this.setState({
matchPos: event.target.checked ? 'start' : 'any'
});
},
onChangeMatchValue(event) {
this.setState({
matchValue: event.target.checked
});
},
onChangeMatchLabel(event) {
this.setState({
matchLabel: event.target.checked
});
},
onChange(value, values) {
this.setState({
value: value
});
logChange(value, values);
},
onChangeMulti(event) {
this.setState({
multi: event.target.checked
});
},
render () {
var matchProp = 'any';
if (this.state.matchLabel && !this.state.matchValue) {
matchProp = 'label';
}
if (!this.state.matchLabel && this.state.matchValue) {
matchProp = 'value';
}
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
searchable
matchProp={matchProp}
matchPos={this.state.matchPos}
options={this.state.options}
onChange={this.onChange}
value={this.state.value}
multi={this.state.multi}
/>
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.multi} onChange={this.onChangeMulti} />
<span className="checkbox-label">Multi-Select</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchValue} onChange={this.onChangeMatchValue} />
<span className="checkbox-label">Match value only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchLabel} onChange={this.onChangeMatchLabel} />
<span className="checkbox-label">Match label only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchPos === 'start'} onChange={this.onChangeMatchStart} />
<span className="checkbox-label">Only include matches from the start of the string</span>
</label>
</div>
</div>
);
}
});
module.exports = ValuesAsNumbersField;
|
ajax/libs/intl-tel-input/4.0.1/js/intlTelInput.js | AMoo-Miki/cdnjs | /*
International Telephone Input v4.0.1
https://github.com/Bluefieldscom/intl-tel-input.git
*/
// wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
(function(factory) {
if (typeof define === "function" && define.amd) {
define([ "jquery" ], function($) {
factory($, window, document);
});
} else {
factory(jQuery, window, document);
}
})(function($, window, document, undefined) {
"use strict";
var pluginName = "intlTelInput", id = 1, // give each instance it's own id for namespaced event handling
defaults = {
// automatically format the number according to the selected country
autoFormat: true,
// if there is just a dial code in the input: remove it on blur, and re-add it on focus
autoHideDialCode: true,
// default country
defaultCountry: "",
// token for ipinfo - required for https or over 1000 daily page views support
ipinfoToken: "",
// don't insert international dial codes
nationalMode: true,
// number type to use for placeholders
numberType: "MOBILE",
// display only these countries
onlyCountries: [],
// the countries at the top of the list. defaults to united states and united kingdom
preferredCountries: [ "us", "gb" ],
// stop the user from typing invalid numbers
preventInvalidNumbers: false,
// specify the path to the libphonenumber script to enable validation/formatting
utilsScript: ""
}, keys = {
UP: 38,
DOWN: 40,
ENTER: 13,
ESC: 27,
PLUS: 43,
A: 65,
Z: 90,
ZERO: 48,
NINE: 57,
SPACE: 32,
BSPACE: 8,
DEL: 46,
CTRL: 17,
CMD1: 91,
// Chrome
CMD2: 224
}, windowLoaded = false;
// keep track of if the window.load event has fired as impossible to check after the fact
$(window).load(function() {
windowLoaded = true;
});
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
// event namespace
this.ns = "." + pluginName + id++;
// Chrome, FF, Safari, IE9+
this.isGoodBrowser = Boolean(element.setSelectionRange);
this.hadInitialPlaceholder = Boolean($(element).attr("placeholder"));
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
var that = this;
// if defaultCountry is set to "auto", we must do a lookup first
if (this.options.defaultCountry == "auto") {
// reset this in case lookup fails
this.options.defaultCountry = "";
var ipinfoURL = "//ipinfo.io";
if (this.options.ipinfoToken) {
ipinfoURL += "?token=" + this.options.ipinfoToken;
}
$.get(ipinfoURL, function(response) {
if (response && response.country) {
that.options.defaultCountry = response.country.toLowerCase();
}
}, "jsonp").always(function() {
that._ready();
});
} else {
this._ready();
}
},
_ready: function() {
// if in nationalMode, disable options relating to dial codes
if (this.options.nationalMode) {
this.options.autoHideDialCode = false;
}
// IE Mobile doesn't support the keypress event (see issue 68) which makes autoFormat impossible
if (navigator.userAgent.match(/IEMobile/i)) {
this.options.autoFormat = false;
}
// process all the data: onlyCountries, preferredCountries etc
this._processCountryData();
// generate the markup
this._generateMarkup();
// set the initial state of the input value and the selected flag
this._setInitialState();
// start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click
this._initListeners();
},
/********************
* PRIVATE METHODS
********************/
// prepare all of the country data, including onlyCountries and preferredCountries options
_processCountryData: function() {
// set the instances country data objects
this._setInstanceCountryData();
// set the preferredCountries property
this._setPreferredCountries();
},
// add a country code to this.countryCodes
_addCountryCode: function(iso2, dialCode, priority) {
if (!(dialCode in this.countryCodes)) {
this.countryCodes[dialCode] = [];
}
var index = priority || 0;
this.countryCodes[dialCode][index] = iso2;
},
// process onlyCountries array if present, and generate the countryCodes map
_setInstanceCountryData: function() {
var i;
// process onlyCountries option
if (this.options.onlyCountries.length) {
this.countries = [];
for (i = 0; i < allCountries.length; i++) {
if ($.inArray(allCountries[i].iso2, this.options.onlyCountries) != -1) {
this.countries.push(allCountries[i]);
}
}
} else {
this.countries = allCountries;
}
// generate countryCodes map
this.countryCodes = {};
for (i = 0; i < this.countries.length; i++) {
var c = this.countries[i];
this._addCountryCode(c.iso2, c.dialCode, c.priority);
// area codes
if (c.areaCodes) {
for (var j = 0; j < c.areaCodes.length; j++) {
// full dial code is country code + dial code
this._addCountryCode(c.iso2, c.dialCode + c.areaCodes[j]);
}
}
}
},
// process preferred countries - iterate through the preferences,
// fetching the country data for each one
_setPreferredCountries: function() {
this.preferredCountries = [];
for (var i = 0; i < this.options.preferredCountries.length; i++) {
var countryCode = this.options.preferredCountries[i], countryData = this._getCountryData(countryCode, false, true);
if (countryData) {
this.preferredCountries.push(countryData);
}
}
},
// generate all of the markup for the plugin: the selected flag overlay, and the dropdown
_generateMarkup: function() {
// telephone input
this.telInput = $(this.element);
// prevent autocomplete as there's no safe, cross-browser event we can react to, so it can easily put the plugin in an inconsistent state e.g. the wrong flag selected for the autocompleted number, which on submit could mean the wrong number is saved (esp in nationalMode)
this.telInput.attr("autocomplete", "off");
// containers (mostly for positioning)
this.telInput.wrap($("<div>", {
"class": "intl-tel-input"
}));
var flagsContainer = $("<div>", {
"class": "flag-dropdown"
}).insertAfter(this.telInput);
// currently selected flag (displayed to left of input)
var selectedFlag = $("<div>", {
"class": "selected-flag"
}).appendTo(flagsContainer);
this.selectedFlagInner = $("<div>", {
"class": "iti-flag"
}).appendTo(selectedFlag);
// CSS triangle
$("<div>", {
"class": "arrow"
}).appendTo(this.selectedFlagInner);
// country list contains: preferred countries, then divider, then all countries
this.countryList = $("<ul>", {
"class": "country-list v-hide"
}).appendTo(flagsContainer);
if (this.preferredCountries.length) {
this._appendListItems(this.preferredCountries, "preferred");
$("<li>", {
"class": "divider"
}).appendTo(this.countryList);
}
this._appendListItems(this.countries, "");
// now we can grab the dropdown height, and hide it properly
this.dropdownHeight = this.countryList.outerHeight();
this.countryList.removeClass("v-hide").addClass("hide");
// on small screens make the dropdown the same width as the input
if (window.innerWidth < 500) {
this.countryList.outerWidth(this.telInput.outerWidth());
}
// this is useful in lots of places
this.countryListItems = this.countryList.children(".country");
},
// add a country <li> to the countryList <ul> container
_appendListItems: function(countries, className) {
// we create so many DOM elements, I decided it was faster to build a temp string
// and then add everything to the DOM in one go at the end
var tmp = "";
// for each country
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
// open the list item
tmp += "<li class='country " + className + "' data-dial-code='" + c.dialCode + "' data-country-code='" + c.iso2 + "'>";
// add the flag
tmp += "<div class='iti-flag " + c.iso2 + "'></div>";
// and the country name and dial code
tmp += "<span class='country-name'>" + c.name + "</span>";
tmp += "<span class='dial-code'>+" + c.dialCode + "</span>";
// close the list item
tmp += "</li>";
}
this.countryList.append(tmp);
},
// set the initial state of the input value and the selected flag
_setInitialState: function() {
var val = this.telInput.val();
// if there is a number, and it's valid, we can go ahead and set the flag, else fall back to default
if (this._getDialCode(val)) {
this._updateFlagFromNumber(val);
} else {
var defaultCountry;
// check the defaultCountry option, else fall back to the first in the list
if (this.options.defaultCountry) {
defaultCountry = this._getCountryData(this.options.defaultCountry, false, false);
} else {
defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0];
}
this._selectFlag(defaultCountry.iso2);
// if empty, insert the default dial code (this function will check !nationalMode and !autoHideDialCode)
if (!val) {
this._updateDialCode(defaultCountry.dialCode, false);
}
}
// format
if (val) {
// this wont be run after _updateDialCode as that's only called if no val
this._updateVal(val, false);
}
},
// initialise the main event listeners: input keyup, and click selected flag
_initListeners: function() {
var that = this;
this._initKeyListeners();
// autoFormat prevents the change event from firing, so we need to check for changes between focus and blur in order to manually trigger it
if (this.options.autoHideDialCode || this.options.autoFormat) {
this._initFocusListeners();
}
// hack for input nested inside label: clicking the selected-flag to open the dropdown would then automatically trigger a 2nd click on the input which would close it again
var label = this.telInput.closest("label");
if (label.length) {
label.on("click" + this.ns, function(e) {
// if the dropdown is closed, then focus the input, else ignore the click
if (that.countryList.hasClass("hide")) {
that.telInput.focus();
} else {
e.preventDefault();
}
});
}
// toggle country dropdown on click
var selectedFlag = this.selectedFlagInner.parent();
selectedFlag.on("click" + this.ns, function(e) {
// only intercept this event if we're opening the dropdown
// else let it bubble up to the top ("click-off-to-close" listener)
// we cannot just stopPropagation as it may be needed to close another instance
if (that.countryList.hasClass("hide") && !that.telInput.prop("disabled") && !that.telInput.prop("readonly")) {
that._showDropdown();
}
});
// if the user has specified the path to the utils script, fetch it on window.load
if (this.options.utilsScript) {
// if the plugin is being initialised after the window.load event has already been fired
if (windowLoaded) {
this.loadUtils();
} else {
// wait until the load event so we don't block any other requests e.g. the flags image
$(window).load(function() {
that.loadUtils();
});
}
}
},
_initKeyListeners: function() {
var that = this;
if (this.options.autoFormat) {
// format number and update flag on keypress
// use keypress event as we want to ignore all input except for a select few keys,
// but we dont want to ignore the navigation keys like the arrows etc.
// NOTE: no point in refactoring this to only bind these listeners on focus/blur because then you would need to have those 2 listeners running the whole time anyway...
this.telInput.on("keypress" + this.ns, function(e) {
// 32 is space, and after that it's all chars (not meta/nav keys)
// this fix is needed for Firefox, which triggers keypress event for some meta/nav keys
// Update: also ignore if this is a metaKey e.g. FF and Safari trigger keypress on the v of Ctrl+v
// Update: also check that we have utils before we do any autoFormat stuff
if (e.which >= keys.SPACE && !e.metaKey && window.intlTelInputUtils && !that.telInput.prop("readonly")) {
e.preventDefault();
// allowed keys are just numeric keys and plus
// we must allow plus for the case where the user does select-all and then hits plus to start typing a new number. we could refine this logic to first check that the selection contains a plus, but that wont work in old browsers, and I think it's overkill anyway
var isAllowedKey = e.which >= keys.ZERO && e.which <= keys.NINE || e.which == keys.PLUS, input = that.telInput[0], noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, max = that.telInput.attr("maxlength"), val = that.telInput.val(), // assumes that if max exists, it is >0
isBelowMax = max ? val.length < max : true;
// first: ensure we dont go over maxlength. we must do this here to prevent adding digits in the middle of the number
// still reformat even if not an allowed key as they could by typing a formatting char, but ignore if there's a selection as doesn't make sense to replace selection with illegal char and then immediately remove it
if (isBelowMax && (isAllowedKey || noSelection)) {
var newChar = isAllowedKey ? String.fromCharCode(e.which) : null;
that._handleInputKey(newChar, true);
// if something has changed, trigger the input event (which was otherwised squashed by the preventDefault)
if (val != that.telInput.val()) {
that.telInput.trigger("input");
}
}
if (!isAllowedKey) {
that.telInput.trigger("invalidkey");
}
}
});
}
// handle keyup event
// for autoFormat: we use keyup to catch cut/paste events and also delete events (after the fact)
this.telInput.on("keyup" + this.ns, function(e) {
// the "enter" key event from selecting a dropdown item is triggered here on the input, because the document.keydown handler that initially handles that event triggers a focus on the input, and so the keyup for that same key event gets triggered here. weird, but just make sure we dont bother doing any re-formatting in this case (we've already done preventDefault in the keydown handler, so it wont actually submit the form or anything).
// ALSO: ignore keyup if readonly
if (e.which == keys.ENTER || that.telInput.prop("readonly")) {} else if (that.options.autoFormat && window.intlTelInputUtils) {
var isCtrl = e.which == keys.CTRL || e.which == keys.CMD1 || e.which == keys.CMD2, input = that.telInput[0], // noSelection defaults to false for bad browsers, else would be reformatting on all ctrl keys e.g. select-all/copy
noSelection = that.isGoodBrowser && input.selectionStart == input.selectionEnd, // cursorAtEnd defaults to false for bad browsers else they would never get a reformat on delete
cursorAtEnd = that.isGoodBrowser && input.selectionStart == that.telInput.val().length;
// if delete in the middle: reformat with no suffix (no need to reformat if delete at end)
// if backspace: reformat with no suffix (need to reformat if at end to remove any lingering suffix - this is a feature)
// if ctrl and no selection (i.e. could have just been a paste): reformat (if cursorAtEnd: add suffix)
if (e.which == keys.DEL && !cursorAtEnd || e.which == keys.BSPACE || isCtrl && noSelection) {
// important to remember never to add suffix on any delete key as can fuck up in ie8 so you can never delete a formatting char at the end
that._handleInputKey(null, isCtrl && cursorAtEnd);
}
// prevent deleting the plus (if not in nationalMode)
if (!that.options.nationalMode) {
var val = that.telInput.val();
if (val.substr(0, 1) != "+") {
// newCursorPos is current pos + 1 to account for the plus we are about to add
var newCursorPos = that.isGoodBrowser ? input.selectionStart + 1 : 0;
that.telInput.val("+" + val);
if (that.isGoodBrowser) {
input.setSelectionRange(newCursorPos, newCursorPos);
}
}
}
} else {
// if no autoFormat, just update flag
that._updateFlagFromNumber(that.telInput.val());
}
});
},
// when autoFormat is enabled: handle various key events on the input: the 2 main situations are 1) adding a new number character, which will replace any selection, reformat, and preserve the cursor position. and 2) reformatting on backspace, or paste event (etc)
_handleInputKey: function(newNumericChar, addSuffix) {
var val = this.telInput.val(), numericBefore = this._getNumeric(val), originalLeftChar, // raw DOM element
input = this.telInput[0], digitsOnRight = 0;
if (this.isGoodBrowser) {
// cursor strategy: maintain the number of digits on the right. we use the right instead of the left so that A) we dont have to account for the new digit (or digits if paste event), and B) we're always on the right side of formatting suffixes
digitsOnRight = this._getDigitsOnRight(val, input.selectionEnd);
// if handling a new number character: insert it in the right place
if (newNumericChar) {
// replace any selection they may have made with the new char
val = val.substr(0, input.selectionStart) + newNumericChar + val.substring(input.selectionEnd, val.length);
} else {
// here we're not handling a new char, we're just doing a re-format (e.g. on delete/backspace/paste, after the fact), but we still need to maintain the cursor position. so make note of the char on the left, and then after the re-format, we'll count in the same number of digits from the right, and then keep going through any formatting chars until we hit the same left char that we had before.
originalLeftChar = val.charAt(input.selectionStart - 1);
}
} else if (newNumericChar) {
val += newNumericChar;
}
// update the number and flag
this.setNumber(val, addSuffix);
val = this.telInput.val();
var numericAfter = this._getNumeric(val), numericIsSame = numericBefore == numericAfter;
if (this.options.preventInvalidNumbers && newNumericChar) {
if (numericIsSame) {
// if we're trying to add a new numeric char and the numeric digits haven't changed, then trigger invalid
this.telInput.trigger("invalidkey");
} else if (numericBefore.length == numericAfter.length) {
// preventInvalidNumbers edge case: adding digit in middle of full number, so a digit gets dropped from the end (numeric digits have changed but are same length)
digitsOnRight--;
}
}
// update the cursor position
if (this.isGoodBrowser) {
var newCursor;
// if it was at the end, keep it there
if (!digitsOnRight) {
newCursor = val.length;
} else {
// else count in the same number of digits from the right
newCursor = this._getCursorFromDigitsOnRight(val, digitsOnRight);
// but if delete/paste etc, keep going left until hit the same left char as before
if (!newNumericChar) {
newCursor = this._getCursorFromLeftChar(val, newCursor, originalLeftChar);
}
}
// set the new cursor
input.setSelectionRange(newCursor, newCursor);
}
},
// we start from the position in guessCursor, and work our way left until we hit the originalLeftChar or a number to make sure that after reformatting the cursor has the same char on the left in the case of a delete etc
_getCursorFromLeftChar: function(val, guessCursor, originalLeftChar) {
for (var i = guessCursor; i > 0; i--) {
var leftChar = val.charAt(i - 1);
if (leftChar == originalLeftChar || $.isNumeric(leftChar)) {
return i;
}
}
return 0;
},
// after a reformat we need to make sure there are still the same number of digits to the right of the cursor
_getCursorFromDigitsOnRight: function(val, digitsOnRight) {
for (var i = val.length - 1; i >= 0; i--) {
if ($.isNumeric(val.charAt(i))) {
if (--digitsOnRight === 0) {
return i;
}
}
}
return 0;
},
// get the number of numeric digits to the right of the cursor so we can reposition the cursor correctly after the reformat has happened
_getDigitsOnRight: function(val, selectionEnd) {
var digitsOnRight = 0;
for (var i = selectionEnd; i < val.length; i++) {
if ($.isNumeric(val.charAt(i))) {
digitsOnRight++;
}
}
return digitsOnRight;
},
// listen for focus and blur
_initFocusListeners: function() {
var that = this;
if (this.options.autoHideDialCode) {
// mousedown decides where the cursor goes, so if we're focusing we must preventDefault as we'll be inserting the dial code, and we want the cursor to be at the end no matter where they click
this.telInput.on("mousedown" + this.ns, function(e) {
if (!that.telInput.is(":focus") && !that.telInput.val()) {
e.preventDefault();
// but this also cancels the focus, so we must trigger that manually
that.telInput.focus();
}
});
}
this.telInput.on("focus" + this.ns, function(e) {
var value = that.telInput.val();
// save this to compare on blur
that.telInput.data("focusVal", value);
// on focus: if empty, insert the dial code for the currently selected flag
if (that.options.autoHideDialCode && !value && !that.telInput.prop("readonly")) {
that._updateVal("+" + that.selectedCountryData.dialCode, true);
// after auto-inserting a dial code, if the first key they hit is '+' then assume they are entering a new number, so remove the dial code. use keypress instead of keydown because keydown gets triggered for the shift key (required to hit the + key), and instead of keyup because that shows the new '+' before removing the old one
that.telInput.one("keypress.plus" + that.ns, function(e) {
if (e.which == keys.PLUS) {
// if autoFormat is enabled, this key event will have already have been handled by another keypress listener (hence we need to add the "+"). if disabled, it will be handled after this by a keyup listener (hence no need to add the "+").
var newVal = that.options.autoFormat && window.intlTelInputUtils ? "+" : "";
that.telInput.val(newVal);
}
});
// after tabbing in, make sure the cursor is at the end we must use setTimeout to get outside of the focus handler as it seems the selection happens after that
setTimeout(function() {
var input = that.telInput[0];
if (that.isGoodBrowser) {
var len = that.telInput.val().length;
input.setSelectionRange(len, len);
}
});
}
});
this.telInput.on("blur" + this.ns, function() {
if (that.options.autoHideDialCode) {
// on blur: if just a dial code then remove it
var value = that.telInput.val(), startsPlus = value.substr(0, 1) == "+";
if (startsPlus) {
var numeric = that._getNumeric(value);
// if just a plus, or if just a dial code
if (!numeric || that.selectedCountryData.dialCode == numeric) {
that.telInput.val("");
}
}
// remove the keypress listener we added on focus
that.telInput.off("keypress.plus" + that.ns);
}
// if autoFormat, we must manually trigger change event if value has changed
if (that.options.autoFormat && window.intlTelInputUtils && that.telInput.val() != that.telInput.data("focusVal")) {
that.telInput.trigger("change");
}
});
},
// extract the numeric digits from the given string
_getNumeric: function(s) {
return s.replace(/\D/g, "");
},
// show the dropdown
_showDropdown: function() {
this._setDropdownPosition();
// update highlighting and scroll to active list item
var activeListItem = this.countryList.children(".active");
this._highlightListItem(activeListItem);
// show it
this.countryList.removeClass("hide");
this._scrollTo(activeListItem);
// bind all the dropdown-related listeners: mouseover, click, click-off, keydown
this._bindDropdownListeners();
// update the arrow
this.selectedFlagInner.children(".arrow").addClass("up");
},
// decide where to position dropdown (depends on position within viewport, and scroll)
_setDropdownPosition: function() {
var inputTop = this.telInput.offset().top, windowTop = $(window).scrollTop(), // dropdownFitsBelow = (dropdownBottom < windowBottom)
dropdownFitsBelow = inputTop + this.telInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop;
// dropdownHeight - 1 for border
var cssTop = !dropdownFitsBelow && dropdownFitsAbove ? "-" + (this.dropdownHeight - 1) + "px" : "";
this.countryList.css("top", cssTop);
},
// we only bind dropdown listeners when the dropdown is open
_bindDropdownListeners: function() {
var that = this;
// when mouse over a list item, just highlight that one
// we add the class "highlight", so if they hit "enter" we know which one to select
this.countryList.on("mouseover" + this.ns, ".country", function(e) {
that._highlightListItem($(this));
});
// listen for country selection
this.countryList.on("click" + this.ns, ".country", function(e) {
that._selectListItem($(this));
});
// click off to close
// (except when this initial opening click is bubbling up)
// we cannot just stopPropagation as it may be needed to close another instance
var isOpening = true;
$("html").on("click" + this.ns, function(e) {
if (!isOpening) {
that._closeDropdown();
}
isOpening = false;
});
// listen for up/down scrolling, enter to select, or letters to jump to country name.
// use keydown as keypress doesn't fire for non-char keys and we want to catch if they
// just hit down and hold it to scroll down (no keyup event).
// listen on the document because that's where key events are triggered if no input has focus
var query = "", queryTimer = null;
$(document).on("keydown" + this.ns, function(e) {
// prevent down key from scrolling the whole page,
// and enter key from submitting a form etc
e.preventDefault();
if (e.which == keys.UP || e.which == keys.DOWN) {
// up and down to navigate
that._handleUpDownKey(e.which);
} else if (e.which == keys.ENTER) {
// enter to select
that._handleEnterKey();
} else if (e.which == keys.ESC) {
// esc to close
that._closeDropdown();
} else if (e.which >= keys.A && e.which <= keys.Z || e.which == keys.SPACE) {
// upper case letters (note: keyup/keydown only return upper case letters)
// jump to countries that start with the query string
if (queryTimer) {
clearTimeout(queryTimer);
}
query += String.fromCharCode(e.which);
that._searchForCountry(query);
// if the timer hits 1 second, reset the query
queryTimer = setTimeout(function() {
query = "";
}, 1e3);
}
});
},
// highlight the next/prev item in the list (and ensure it is visible)
_handleUpDownKey: function(key) {
var current = this.countryList.children(".highlight").first();
var next = key == keys.UP ? current.prev() : current.next();
if (next.length) {
// skip the divider
if (next.hasClass("divider")) {
next = key == keys.UP ? next.prev() : next.next();
}
this._highlightListItem(next);
this._scrollTo(next);
}
},
// select the currently highlighted item
_handleEnterKey: function() {
var currentCountry = this.countryList.children(".highlight").first();
if (currentCountry.length) {
this._selectListItem(currentCountry);
}
},
// find the first list item whose name starts with the query string
_searchForCountry: function(query) {
for (var i = 0; i < this.countries.length; i++) {
if (this._startsWith(this.countries[i].name, query)) {
var listItem = this.countryList.children("[data-country-code=" + this.countries[i].iso2 + "]").not(".preferred");
// update highlighting and scroll
this._highlightListItem(listItem);
this._scrollTo(listItem, true);
break;
}
}
},
// check if (uppercase) string a starts with string b
_startsWith: function(a, b) {
return a.substr(0, b.length).toUpperCase() == b;
},
// update the input's value to the given val
// if autoFormat=true, format it first according to the country-specific formatting rules
_updateVal: function(val, addSuffix) {
var formatted;
if (this.options.autoFormat && window.intlTelInputUtils) {
formatted = intlTelInputUtils.formatNumber(val, this.selectedCountryData.iso2, addSuffix, this.options.preventInvalidNumbers);
// ensure we dont go over maxlength. we must do this here to truncate any formatting suffix, and also handle paste events
var max = this.telInput.attr("maxlength");
if (max && formatted.length > max) {
formatted = formatted.substr(0, max);
}
} else {
// no autoFormat, so just insert the original value
formatted = val;
}
this.telInput.val(formatted);
},
// check if need to select a new flag based on the given number
_updateFlagFromNumber: function(number) {
// if we're in nationalMode and we're on US/Canada, make sure the number starts with a +1 so _getDialCode will be able to extract the area code
// update: if we dont yet have selectedCountryData, but we're here (trying to update the flag from the number), that means we're initialising the plugin with a number that already has a dial code, so fine to ignore this bit
if (this.options.nationalMode && this.selectedCountryData && this.selectedCountryData.dialCode == "1" && number.substr(0, 1) != "+") {
number = "+1" + number;
}
// try and extract valid dial code from input
var dialCode = this._getDialCode(number);
if (dialCode) {
// check if one of the matching countries is already selected
var countryCodes = this.countryCodes[this._getNumeric(dialCode)], alreadySelected = false;
if (this.selectedCountryData) {
for (var i = 0; i < countryCodes.length; i++) {
if (countryCodes[i] == this.selectedCountryData.iso2) {
alreadySelected = true;
}
}
}
// if a matching country is not already selected (or this is an unknown NANP area code): choose the first in the list
if (!alreadySelected || this._isUnknownNanp(number, dialCode)) {
// if using onlyCountries option, countryCodes[0] may be empty, so we must find the first non-empty index
for (var j = 0; j < countryCodes.length; j++) {
if (countryCodes[j]) {
this._selectFlag(countryCodes[j]);
break;
}
}
}
}
},
// check if the given number contains an unknown area code from the North American Numbering Plan i.e. the only dialCode that could be extracted was +1 but the actual number's length is >=4
_isUnknownNanp: function(number, dialCode) {
return dialCode == "+1" && this._getNumeric(number).length >= 4;
},
// remove highlighting from other list items and highlight the given item
_highlightListItem: function(listItem) {
this.countryListItems.removeClass("highlight");
listItem.addClass("highlight");
},
// find the country data for the given country code
// the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array
_getCountryData: function(countryCode, ignoreOnlyCountriesOption, allowFail) {
var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
for (var i = 0; i < countryList.length; i++) {
if (countryList[i].iso2 == countryCode) {
return countryList[i];
}
}
if (allowFail) {
return null;
} else {
throw new Error("No country data for '" + countryCode + "'");
}
},
// select the given flag, update the placeholder and the active list item
_selectFlag: function(countryCode) {
// do this first as it will throw an error and stop if countryCode is invalid
this.selectedCountryData = this._getCountryData(countryCode, false, false);
this.selectedFlagInner.attr("class", "iti-flag " + countryCode);
// update the selected country's title attribute
var title = this.selectedCountryData.name + ": +" + this.selectedCountryData.dialCode;
this.selectedFlagInner.parent().attr("title", title);
// and the input's placeholder
this._updatePlaceholder();
// update the active list item
var listItem = this.countryListItems.children(".iti-flag." + countryCode).first().parent();
this.countryListItems.removeClass("active");
listItem.addClass("active");
},
// update the input placeholder to an example number from the currently selected country
_updatePlaceholder: function() {
if (window.intlTelInputUtils && !this.hadInitialPlaceholder) {
var iso2 = this.selectedCountryData.iso2, numberType = intlTelInputUtils.numberType[this.options.numberType || "FIXED_LINE"], placeholder = intlTelInputUtils.getExampleNumber(iso2, this.options.nationalMode, numberType);
this.telInput.attr("placeholder", placeholder);
}
},
// called when the user selects a list item from the dropdown
_selectListItem: function(listItem) {
// update selected flag and active list item
var countryCode = listItem.attr("data-country-code");
this._selectFlag(countryCode);
this._closeDropdown();
this._updateDialCode(listItem.attr("data-dial-code"), true);
// always fire the change event as even if nationalMode=true (and we haven't updated the input val), the system as a whole has still changed - see country-sync example. think of it as making a selection from a select element.
this.telInput.trigger("change");
// focus the input
this.telInput.focus();
},
// close the dropdown and unbind any listeners
_closeDropdown: function() {
this.countryList.addClass("hide");
// update the arrow
this.selectedFlagInner.children(".arrow").removeClass("up");
// unbind key events
$(document).off(this.ns);
// unbind click-off-to-close
$("html").off(this.ns);
// unbind hover and click listeners
this.countryList.off(this.ns);
},
// check if an element is visible within it's container, else scroll until it is
_scrollTo: function(element, middle) {
var container = this.countryList, containerHeight = container.height(), containerTop = container.offset().top, containerBottom = containerTop + containerHeight, elementHeight = element.outerHeight(), elementTop = element.offset().top, elementBottom = elementTop + elementHeight, newScrollTop = elementTop - containerTop + container.scrollTop(), middleOffset = containerHeight / 2 - elementHeight / 2;
if (elementTop < containerTop) {
// scroll up
if (middle) {
newScrollTop -= middleOffset;
}
container.scrollTop(newScrollTop);
} else if (elementBottom > containerBottom) {
// scroll down
if (middle) {
newScrollTop += middleOffset;
}
var heightDifference = containerHeight - elementHeight;
container.scrollTop(newScrollTop - heightDifference);
}
},
// replace any existing dial code with the new one (if not in nationalMode)
// also we need to know if we're focusing for a couple of reasons e.g. if so, we want to add any formatting suffix, also if the input is empty and we're not in nationalMode, then we want to insert the dial code
_updateDialCode: function(newDialCode, focusing) {
var inputVal = this.telInput.val(), newNumber;
// save having to pass this every time
newDialCode = "+" + newDialCode;
if (this.options.nationalMode && inputVal.substr(0, 1) != "+") {
// if nationalMode, we just want to re-format
newNumber = inputVal;
} else if (inputVal) {
// if the previous number contained a valid dial code, replace it
// (if more than just a plus character)
var prevDialCode = this._getDialCode(inputVal);
if (prevDialCode.length > 1) {
newNumber = inputVal.replace(prevDialCode, newDialCode);
} else {
// if the previous number didn't contain a dial code, we should persist it
var existingNumber = inputVal.substr(0, 1) != "+" ? $.trim(inputVal) : "";
newNumber = newDialCode + existingNumber;
}
} else {
newNumber = !this.options.autoHideDialCode || focusing ? newDialCode : "";
}
this._updateVal(newNumber, focusing);
},
// try and extract a valid international dial code from a full telephone number
// Note: returns the raw string inc plus character and any whitespace/dots etc
_getDialCode: function(number) {
var dialCode = "";
// only interested in international numbers (starting with a plus)
if (number.charAt(0) == "+") {
var numericChars = "";
// iterate over chars
for (var i = 0; i < number.length; i++) {
var c = number.charAt(i);
// if char is number
if ($.isNumeric(c)) {
numericChars += c;
// if current numericChars make a valid dial code
if (this.countryCodes[numericChars]) {
// store the actual raw string (useful for matching later)
dialCode = number.substr(0, i + 1);
}
// longest dial code is 4 chars
if (numericChars.length == 4) {
break;
}
}
}
}
return dialCode;
},
/********************
* PUBLIC METHODS
********************/
// remove plugin
destroy: function() {
// make sure the dropdown is closed (and unbind listeners)
this._closeDropdown();
// key events, and focus/blur events if autoHideDialCode=true
this.telInput.off(this.ns);
// click event to open dropdown
this.selectedFlagInner.parent().off(this.ns);
// label click hack
this.telInput.closest("label").off(this.ns);
// remove markup
var container = this.telInput.parent();
container.before(this.telInput).remove();
},
// format the number to the given type
getNumber: function(type) {
if (window.intlTelInputUtils) {
return intlTelInputUtils.formatNumberByType(this.telInput.val(), this.selectedCountryData.iso2, type);
}
return "";
},
// get the type of the entered number e.g. landline/mobile
getNumberType: function() {
if (window.intlTelInputUtils) {
return intlTelInputUtils.getNumberType(this.telInput.val(), this.selectedCountryData.iso2);
}
return -99;
},
// get the country data for the currently selected flag
getSelectedCountryData: function() {
// if this is undefined, the plugin will return it's instance instead, so in that case an empty object makes more sense
return this.selectedCountryData || {};
},
// get the validation error
getValidationError: function() {
if (window.intlTelInputUtils) {
return intlTelInputUtils.getValidationError(this.telInput.val(), this.selectedCountryData.iso2);
}
return -99;
},
// validate the input val - assumes the global function isValidNumber (from utilsScript)
isValidNumber: function() {
var val = $.trim(this.telInput.val()), countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : "", // libphonenumber allows alpha chars, but in order to allow that, we'd need a method to retrieve the processed number, with letters replaced with numbers
containsAlpha = /[a-zA-Z]/.test(val);
if (!containsAlpha && window.intlTelInputUtils) {
return intlTelInputUtils.isValidNumber(val, countryCode);
}
return false;
},
// load the utils script
loadUtils: function(path) {
var utilsScript = path || this.options.utilsScript;
if (!$.fn[pluginName].loadedUtilsScript && utilsScript) {
// don't do this twice! (dont just check if the global intlTelInputUtils exists as if init plugin multiple times in quick succession, it may not have finished loading yet)
$.fn[pluginName].loadedUtilsScript = true;
// dont use $.getScript as it prevents caching
$.ajax({
url: utilsScript,
success: function() {
// tell all instances the utils are ready
$(".intl-tel-input input").intlTelInput("utilsLoaded");
},
dataType: "script",
cache: true
});
}
},
// update the selected flag, and update the input val accordingly
selectCountry: function(countryCode) {
// check if already selected
if (!this.selectedFlagInner.hasClass(countryCode)) {
this._selectFlag(countryCode);
this._updateDialCode(this.selectedCountryData.dialCode, false);
}
},
// set the input value and update the flag
setNumber: function(number, addSuffix) {
// ensure starts with plus
if (!this.options.nationalMode && number.substr(0, 1) != "+") {
number = "+" + number;
}
// we must update the flag first, which updates this.selectedCountryData, which is used later for formatting the number before displaying it
this._updateFlagFromNumber(number);
this._updateVal(number, addSuffix);
},
// this is called when the utils are ready
utilsLoaded: function() {
// if autoFormat is enabled and there's an initial value in the input, then format it
if (this.options.autoFormat && this.telInput.val()) {
this._updateVal(this.telInput.val());
}
this._updatePlaceholder();
}
};
// adapted to allow public functions
// using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate
$.fn[pluginName] = function(options) {
var args = arguments;
// Is the first parameter an object (options), or was omitted,
// instantiate a new instance of the plugin.
if (options === undefined || typeof options === "object") {
return this.each(function() {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
} else if (typeof options === "string" && options[0] !== "_" && options !== "init") {
// If the first parameter is a string and it doesn't start
// with an underscore or "contains" the `init`-function,
// treat this as a call to a public method.
// Cache the method call to make it possible to return a value
var returns;
this.each(function() {
var instance = $.data(this, "plugin_" + pluginName);
// Tests that there's already a plugin-instance
// and checks that the requested public method exists
if (instance instanceof Plugin && typeof instance[options] === "function") {
// Call the method of our plugin instance,
// and pass it the supplied arguments.
returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
// Allow instances to be destroyed via the 'destroy' method
if (options === "destroy") {
$.data(this, "plugin_" + pluginName, null);
}
});
// If the earlier cached method gives a value back return the value,
// otherwise return this to preserve chainability.
return returns !== undefined ? returns : this;
}
};
/********************
* STATIC METHODS
********************/
// get the country data object
$.fn[pluginName].getCountryData = function() {
return allCountries;
};
// Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
// jshint -W100
// Array of country objects for the flag dropdown.
// Each contains a name, country code (ISO 3166-1 alpha-2) and dial code.
// Originally from https://github.com/mledoze/countries
// then modified using the following JavaScript (NOW OUT OF DATE):
/*
var result = [];
_.each(countries, function(c) {
// ignore countries without a dial code
if (c.callingCode[0].length) {
result.push({
// var locals contains country names with localised versions in brackets
n: _.findWhere(locals, {
countryCode: c.cca2
}).name,
i: c.cca2.toLowerCase(),
d: c.callingCode[0]
});
}
});
JSON.stringify(result);
*/
// then with a couple of manual re-arrangements to be alphabetical
// then changed Kazakhstan from +76 to +7
// and Vatican City from +379 to +39 (see issue 50)
// and Caribean Netherlands from +5997 to +599
// and Curacao from +5999 to +599
// Removed: Åland Islands, Christmas Island, Cocos Islands, Guernsey, Isle of Man, Jersey, Kosovo, Mayotte, Pitcairn Islands, South Georgia, Svalbard, Western Sahara
// Update: converted objects to arrays to save bytes!
// Update: added "priority" for countries with the same dialCode as others
// Update: added array of area codes for countries with the same dialCode as others
// So each country array has the following information:
// [
// Country name,
// iso2 code,
// International dial code,
// Order (if >1 country with same dial code),
// Area codes (if >1 country with same dial code)
// ]
var allCountries = [ [ "Afghanistan (افغانستان)", "af", "93" ], [ "Albania (Shqipëri)", "al", "355" ], [ "Algeria (الجزائر)", "dz", "213" ], [ "American Samoa", "as", "1684" ], [ "Andorra", "ad", "376" ], [ "Angola", "ao", "244" ], [ "Anguilla", "ai", "1264" ], [ "Antigua and Barbuda", "ag", "1268" ], [ "Argentina", "ar", "54" ], [ "Armenia (Հայաստան)", "am", "374" ], [ "Aruba", "aw", "297" ], [ "Australia", "au", "61" ], [ "Austria (Österreich)", "at", "43" ], [ "Azerbaijan (Azərbaycan)", "az", "994" ], [ "Bahamas", "bs", "1242" ], [ "Bahrain (البحرين)", "bh", "973" ], [ "Bangladesh (বাংলাদেশ)", "bd", "880" ], [ "Barbados", "bb", "1246" ], [ "Belarus (Беларусь)", "by", "375" ], [ "Belgium (België)", "be", "32" ], [ "Belize", "bz", "501" ], [ "Benin (Bénin)", "bj", "229" ], [ "Bermuda", "bm", "1441" ], [ "Bhutan (འབྲུག)", "bt", "975" ], [ "Bolivia", "bo", "591" ], [ "Bosnia and Herzegovina (Босна и Херцеговина)", "ba", "387" ], [ "Botswana", "bw", "267" ], [ "Brazil (Brasil)", "br", "55" ], [ "British Indian Ocean Territory", "io", "246" ], [ "British Virgin Islands", "vg", "1284" ], [ "Brunei", "bn", "673" ], [ "Bulgaria (България)", "bg", "359" ], [ "Burkina Faso", "bf", "226" ], [ "Burundi (Uburundi)", "bi", "257" ], [ "Cambodia (កម្ពុជា)", "kh", "855" ], [ "Cameroon (Cameroun)", "cm", "237" ], [ "Canada", "ca", "1", 1, [ "204", "226", "236", "249", "250", "289", "306", "343", "365", "387", "403", "416", "418", "431", "437", "438", "450", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "705", "709", "742", "778", "780", "782", "807", "819", "825", "867", "873", "902", "905" ] ], [ "Cape Verde (Kabu Verdi)", "cv", "238" ], [ "Caribbean Netherlands", "bq", "599", 1 ], [ "Cayman Islands", "ky", "1345" ], [ "Central African Republic (République centrafricaine)", "cf", "236" ], [ "Chad (Tchad)", "td", "235" ], [ "Chile", "cl", "56" ], [ "China (中国)", "cn", "86" ], [ "Colombia", "co", "57" ], [ "Comoros (جزر القمر)", "km", "269" ], [ "Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243" ], [ "Congo (Republic) (Congo-Brazzaville)", "cg", "242" ], [ "Cook Islands", "ck", "682" ], [ "Costa Rica", "cr", "506" ], [ "Côte d’Ivoire", "ci", "225" ], [ "Croatia (Hrvatska)", "hr", "385" ], [ "Cuba", "cu", "53" ], [ "Curaçao", "cw", "599", 0 ], [ "Cyprus (Κύπρος)", "cy", "357" ], [ "Czech Republic (Česká republika)", "cz", "420" ], [ "Denmark (Danmark)", "dk", "45" ], [ "Djibouti", "dj", "253" ], [ "Dominica", "dm", "1767" ], [ "Dominican Republic (República Dominicana)", "do", "1", 2, [ "809", "829", "849" ] ], [ "Ecuador", "ec", "593" ], [ "Egypt (مصر)", "eg", "20" ], [ "El Salvador", "sv", "503" ], [ "Equatorial Guinea (Guinea Ecuatorial)", "gq", "240" ], [ "Eritrea", "er", "291" ], [ "Estonia (Eesti)", "ee", "372" ], [ "Ethiopia", "et", "251" ], [ "Falkland Islands (Islas Malvinas)", "fk", "500" ], [ "Faroe Islands (Føroyar)", "fo", "298" ], [ "Fiji", "fj", "679" ], [ "Finland (Suomi)", "fi", "358" ], [ "France", "fr", "33" ], [ "French Guiana (Guyane française)", "gf", "594" ], [ "French Polynesia (Polynésie française)", "pf", "689" ], [ "Gabon", "ga", "241" ], [ "Gambia", "gm", "220" ], [ "Georgia (საქართველო)", "ge", "995" ], [ "Germany (Deutschland)", "de", "49" ], [ "Ghana (Gaana)", "gh", "233" ], [ "Gibraltar", "gi", "350" ], [ "Greece (Ελλάδα)", "gr", "30" ], [ "Greenland (Kalaallit Nunaat)", "gl", "299" ], [ "Grenada", "gd", "1473" ], [ "Guadeloupe", "gp", "590", 0 ], [ "Guam", "gu", "1671" ], [ "Guatemala", "gt", "502" ], [ "Guinea (Guinée)", "gn", "224" ], [ "Guinea-Bissau (Guiné Bissau)", "gw", "245" ], [ "Guyana", "gy", "592" ], [ "Haiti", "ht", "509" ], [ "Honduras", "hn", "504" ], [ "Hong Kong (香港)", "hk", "852" ], [ "Hungary (Magyarország)", "hu", "36" ], [ "Iceland (Ísland)", "is", "354" ], [ "India (भारत)", "in", "91" ], [ "Indonesia", "id", "62" ], [ "Iran (ایران)", "ir", "98" ], [ "Iraq (العراق)", "iq", "964" ], [ "Ireland", "ie", "353" ], [ "Israel (ישראל)", "il", "972" ], [ "Italy (Italia)", "it", "39", 0 ], [ "Jamaica", "jm", "1876" ], [ "Japan (日本)", "jp", "81" ], [ "Jordan (الأردن)", "jo", "962" ], [ "Kazakhstan (Казахстан)", "kz", "7", 1 ], [ "Kenya", "ke", "254" ], [ "Kiribati", "ki", "686" ], [ "Kuwait (الكويت)", "kw", "965" ], [ "Kyrgyzstan (Кыргызстан)", "kg", "996" ], [ "Laos (ລາວ)", "la", "856" ], [ "Latvia (Latvija)", "lv", "371" ], [ "Lebanon (لبنان)", "lb", "961" ], [ "Lesotho", "ls", "266" ], [ "Liberia", "lr", "231" ], [ "Libya (ليبيا)", "ly", "218" ], [ "Liechtenstein", "li", "423" ], [ "Lithuania (Lietuva)", "lt", "370" ], [ "Luxembourg", "lu", "352" ], [ "Macau (澳門)", "mo", "853" ], [ "Macedonia (FYROM) (Македонија)", "mk", "389" ], [ "Madagascar (Madagasikara)", "mg", "261" ], [ "Malawi", "mw", "265" ], [ "Malaysia", "my", "60" ], [ "Maldives", "mv", "960" ], [ "Mali", "ml", "223" ], [ "Malta", "mt", "356" ], [ "Marshall Islands", "mh", "692" ], [ "Martinique", "mq", "596" ], [ "Mauritania (موريتانيا)", "mr", "222" ], [ "Mauritius (Moris)", "mu", "230" ], [ "Mexico (México)", "mx", "52" ], [ "Micronesia", "fm", "691" ], [ "Moldova (Republica Moldova)", "md", "373" ], [ "Monaco", "mc", "377" ], [ "Mongolia (Монгол)", "mn", "976" ], [ "Montenegro (Crna Gora)", "me", "382" ], [ "Montserrat", "ms", "1664" ], [ "Morocco (المغرب)", "ma", "212" ], [ "Mozambique (Moçambique)", "mz", "258" ], [ "Myanmar (Burma) (မြန်မာ)", "mm", "95" ], [ "Namibia (Namibië)", "na", "264" ], [ "Nauru", "nr", "674" ], [ "Nepal (नेपाल)", "np", "977" ], [ "Netherlands (Nederland)", "nl", "31" ], [ "New Caledonia (Nouvelle-Calédonie)", "nc", "687" ], [ "New Zealand", "nz", "64" ], [ "Nicaragua", "ni", "505" ], [ "Niger (Nijar)", "ne", "227" ], [ "Nigeria", "ng", "234" ], [ "Niue", "nu", "683" ], [ "Norfolk Island", "nf", "672" ], [ "North Korea (조선 민주주의 인민 공화국)", "kp", "850" ], [ "Northern Mariana Islands", "mp", "1670" ], [ "Norway (Norge)", "no", "47" ], [ "Oman (عُمان)", "om", "968" ], [ "Pakistan (پاکستان)", "pk", "92" ], [ "Palau", "pw", "680" ], [ "Palestine (فلسطين)", "ps", "970" ], [ "Panama (Panamá)", "pa", "507" ], [ "Papua New Guinea", "pg", "675" ], [ "Paraguay", "py", "595" ], [ "Peru (Perú)", "pe", "51" ], [ "Philippines", "ph", "63" ], [ "Poland (Polska)", "pl", "48" ], [ "Portugal", "pt", "351" ], [ "Puerto Rico", "pr", "1", 3, [ "787", "939" ] ], [ "Qatar (قطر)", "qa", "974" ], [ "Réunion (La Réunion)", "re", "262" ], [ "Romania (România)", "ro", "40" ], [ "Russia (Россия)", "ru", "7", 0 ], [ "Rwanda", "rw", "250" ], [ "Saint Barthélemy (Saint-Barthélemy)", "bl", "590", 1 ], [ "Saint Helena", "sh", "290" ], [ "Saint Kitts and Nevis", "kn", "1869" ], [ "Saint Lucia", "lc", "1758" ], [ "Saint Martin (Saint-Martin (partie française))", "mf", "590", 2 ], [ "Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508" ], [ "Saint Vincent and the Grenadines", "vc", "1784" ], [ "Samoa", "ws", "685" ], [ "San Marino", "sm", "378" ], [ "São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239" ], [ "Saudi Arabia (المملكة العربية السعودية)", "sa", "966" ], [ "Senegal (Sénégal)", "sn", "221" ], [ "Serbia (Србија)", "rs", "381" ], [ "Seychelles", "sc", "248" ], [ "Sierra Leone", "sl", "232" ], [ "Singapore", "sg", "65" ], [ "Sint Maarten", "sx", "1721" ], [ "Slovakia (Slovensko)", "sk", "421" ], [ "Slovenia (Slovenija)", "si", "386" ], [ "Solomon Islands", "sb", "677" ], [ "Somalia (Soomaaliya)", "so", "252" ], [ "South Africa", "za", "27" ], [ "South Korea (대한민국)", "kr", "82" ], [ "South Sudan (جنوب السودان)", "ss", "211" ], [ "Spain (España)", "es", "34" ], [ "Sri Lanka (ශ්රී ලංකාව)", "lk", "94" ], [ "Sudan (السودان)", "sd", "249" ], [ "Suriname", "sr", "597" ], [ "Swaziland", "sz", "268" ], [ "Sweden (Sverige)", "se", "46" ], [ "Switzerland (Schweiz)", "ch", "41" ], [ "Syria (سوريا)", "sy", "963" ], [ "Taiwan (台灣)", "tw", "886" ], [ "Tajikistan", "tj", "992" ], [ "Tanzania", "tz", "255" ], [ "Thailand (ไทย)", "th", "66" ], [ "Timor-Leste", "tl", "670" ], [ "Togo", "tg", "228" ], [ "Tokelau", "tk", "690" ], [ "Tonga", "to", "676" ], [ "Trinidad and Tobago", "tt", "1868" ], [ "Tunisia (تونس)", "tn", "216" ], [ "Turkey (Türkiye)", "tr", "90" ], [ "Turkmenistan", "tm", "993" ], [ "Turks and Caicos Islands", "tc", "1649" ], [ "Tuvalu", "tv", "688" ], [ "U.S. Virgin Islands", "vi", "1340" ], [ "Uganda", "ug", "256" ], [ "Ukraine (Україна)", "ua", "380" ], [ "United Arab Emirates (الإمارات العربية المتحدة)", "ae", "971" ], [ "United Kingdom", "gb", "44" ], [ "United States", "us", "1", 0 ], [ "Uruguay", "uy", "598" ], [ "Uzbekistan (Oʻzbekiston)", "uz", "998" ], [ "Vanuatu", "vu", "678" ], [ "Vatican City (Città del Vaticano)", "va", "39", 1 ], [ "Venezuela", "ve", "58" ], [ "Vietnam (Việt Nam)", "vn", "84" ], [ "Wallis and Futuna", "wf", "681" ], [ "Yemen (اليمن)", "ye", "967" ], [ "Zambia", "zm", "260" ], [ "Zimbabwe", "zw", "263" ] ];
// loop over all of the countries above
for (var i = 0; i < allCountries.length; i++) {
var c = allCountries[i];
allCountries[i] = {
name: c[0],
iso2: c[1],
dialCode: c[2],
priority: c[3] || 0,
areaCodes: c[4] || null
};
}
}); |
ajax/libs/highstock/1.3.7/highstock.src.js | bspaulding/cdnjs | // ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
/**
* @license Highstock JS v1.3.7 (2013-10-24)
*
* (c) 2009-2013 Torstein Hønsi
*
* License: www.highcharts.com/license
*/
// JSLint options:
/*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */
(function () {
// encapsulated variables
var UNDEFINED,
doc = document,
win = window,
math = Math,
mathRound = math.round,
mathFloor = math.floor,
mathCeil = math.ceil,
mathMax = math.max,
mathMin = math.min,
mathAbs = math.abs,
mathCos = math.cos,
mathSin = math.sin,
mathPI = math.PI,
deg2rad = mathPI * 2 / 360,
// some variables
userAgent = navigator.userAgent,
isOpera = win.opera,
isIE = /msie/i.test(userAgent) && !isOpera,
docMode8 = doc.documentMode === 8,
isWebKit = /AppleWebKit/.test(userAgent),
isFirefox = /Firefox/.test(userAgent),
isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS = 'http://www.w3.org/2000/svg',
hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
Renderer,
hasTouch = doc.documentElement.ontouchstart !== UNDEFINED,
symbolSizes = {},
idCounter = 0,
garbageBin,
defaultOptions,
dateFormat, // function
globalAnimation,
pathAnim,
timeUnits,
noop = function () {},
charts = [],
PRODUCT = 'Highstock',
VERSION = '1.3.7',
// some constants for frequently used strings
DIV = 'div',
ABSOLUTE = 'absolute',
RELATIVE = 'relative',
HIDDEN = 'hidden',
PREFIX = 'highcharts-',
VISIBLE = 'visible',
PX = 'px',
NONE = 'none',
M = 'M',
L = 'L',
/*
* Empirical lowest possible opacities for TRACKER_FILL
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable
//TRACKER_FILL = 'rgba(192,192,192,0.5)',
NORMAL_STATE = '',
HOVER_STATE = 'hover',
SELECT_STATE = 'select',
MILLISECOND = 'millisecond',
SECOND = 'second',
MINUTE = 'minute',
HOUR = 'hour',
DAY = 'day',
WEEK = 'week',
MONTH = 'month',
YEAR = 'year',
// constants for attributes
LINEAR_GRADIENT = 'linearGradient',
STOPS = 'stops',
STROKE_WIDTH = 'stroke-width',
// time methods, changed based on whether or not UTC is used
makeTime,
getMinutes,
getHours,
getDay,
getDate,
getMonth,
getFullYear,
setMinutes,
setHours,
setDate,
setMonth,
setFullYear,
// lookup over the types and the associated classes
seriesTypes = {};
// The Highcharts namespace
win.Highcharts = win.Highcharts ? error(16, true) : {};
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
function extend(a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
}
/**
* Deep merge two or more objects and return a third object.
* Previously this function redirected to jQuery.extend(true), but this had two limitations.
* First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
* it copied properties from extended prototypes.
*/
function merge() {
var i,
len = arguments.length,
ret = {},
doCopy = function (copy, original) {
var value, key;
// An object is replacing a primitive
if (typeof copy !== 'object') {
copy = {};
}
for (key in original) {
if (original.hasOwnProperty(key)) {
value = original[key];
// Copy the contents of objects, but not arrays or DOM nodes
if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
&& typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value);
// Primitives and arrays are copied over directly
} else {
copy[key] = original[key];
}
}
}
return copy;
};
// For each argument, extend the return
for (i = 0; i < len; i++) {
ret = doCopy(ret, arguments[i]);
}
return ret;
}
/**
* Take an array and turn into a hash with even number arguments as keys and odd numbers as
* values. Allows creating constants for commonly used style properties, attributes etc.
* Avoid it in performance critical situations like looping
*/
function hash() {
var i = 0,
args = arguments,
length = args.length,
obj = {};
for (; i < length; i++) {
obj[args[i++]] = args[i];
}
return obj;
}
/**
* Shortcut for parseInt
* @param {Object} s
* @param {Number} mag Magnitude
*/
function pInt(s, mag) {
return parseInt(s, mag || 10);
}
/**
* Check for string
* @param {Object} s
*/
function isString(s) {
return typeof s === 'string';
}
/**
* Check for object
* @param {Object} obj
*/
function isObject(obj) {
return typeof obj === 'object';
}
/**
* Check for array
* @param {Object} obj
*/
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
/**
* Check for number
* @param {Object} n
*/
function isNumber(n) {
return typeof n === 'number';
}
function log2lin(num) {
return math.log(num) / math.LN10;
}
function lin2log(num) {
return math.pow(10, num);
}
/**
* Remove last occurence of an item from an array
* @param {Array} arr
* @param {Mixed} item
*/
function erase(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
}
/**
* Returns true if the object is not null or undefined. Like MooTools' $.defined.
* @param {Object} obj
*/
function defined(obj) {
return obj !== UNDEFINED && obj !== null;
}
/**
* Set or get an attribute or an object of attributes. Can't use jQuery attr because
* it attempts to set expando properties on the SVG element, which is not allowed.
*
* @param {Object} elem The DOM element to receive the attribute(s)
* @param {String|Object} prop The property or an abject of key-value pairs
* @param {String} value The value if a single property is set
*/
function attr(elem, prop, value) {
var key,
setAttribute = 'setAttribute',
ret;
// if the prop is a string
if (isString(prop)) {
// set the value
if (defined(value)) {
elem[setAttribute](prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (defined(prop) && isObject(prop)) {
for (key in prop) {
elem[setAttribute](key, prop[key]);
}
}
return ret;
}
/**
* Check if an element is an array, and if not, make it into an array. Like
* MooTools' $.splat.
*/
function splat(obj) {
return isArray(obj) ? obj : [obj];
}
/**
* Return the first value that is defined. Like MooTools' $.pick.
*/
function pick() {
var args = arguments,
i,
arg,
length = args.length;
for (i = 0; i < length; i++) {
arg = args[i];
if (typeof arg !== 'undefined' && arg !== null) {
return arg;
}
}
}
/**
* Set CSS on a given element
* @param {Object} el
* @param {Object} styles Style object with camel case property names
*/
function css(el, styles) {
if (isIE) {
if (styles && styles.opacity !== UNDEFINED) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
extend(el.style, styles);
}
/**
* Utility function to create element with attributes and styles
* @param {Object} tag
* @param {Object} attribs
* @param {Object} styles
* @param {Object} parent
* @param {Object} nopad
*/
function createElement(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag);
if (attribs) {
extend(el, attribs);
}
if (nopad) {
css(el, {padding: 0, border: NONE, margin: 0});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
}
/**
* Extend a prototyped class by new members
* @param {Object} parent
* @param {Object} members
*/
function extendClass(parent, members) {
var object = function () {};
object.prototype = new parent();
extend(object.prototype, members);
return object;
}
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
function numberFormat(number, decimals, decPoint, thousandsSep) {
var lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = +number || 0,
c = decimals === -1 ?
(n.toString().split('.')[1] || '').length : // preserve decimals
(isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
s = n < 0 ? "-" : "",
i = String(pInt(n = mathAbs(n).toFixed(c))),
j = i.length > 3 ? i.length % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
(c ? d + mathAbs(n - i).toFixed(c).slice(2) : "");
}
/**
* Pad a string to a given length by adding 0 to the beginning
* @param {Number} number
* @param {Number} length
*/
function pad(number, length) {
// Create an array of the remaining length +1 and join it with 0's
return new Array((length || 2) + 1 - String(number).length).join(0) + number;
}
/**
* Wrap a method with extended functionality, preserving the original function
* @param {Object} obj The context object that the method belongs to
* @param {String} method The name of the method to extend
* @param {Function} func A wrapper function callback. This function is called with the same arguments
* as the original function, except that the original function is unshifted and passed as the first
* argument.
*/
function wrap(obj, method, func) {
var proceed = obj[method];
obj[method] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
}
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
dateFormat = function (format, timestamp, capitalize) {
if (!defined(timestamp) || isNaN(timestamp)) {
return 'Invalid date';
}
format = pick(format, '%Y-%m-%d %H:%M:%S');
var date = new Date(timestamp),
key, // used in for constuct below
// get the basic time values
hours = date[getHours](),
day = date[getDay](),
dayOfMonth = date[getDate](),
month = date[getMonth](),
fullYear = date[getFullYear](),
lang = defaultOptions.lang,
langWeekdays = lang.weekdays,
// List all format keys. Custom formats can be added from the outside.
replacements = extend({
// Day
'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': dayOfMonth, // Day of the month, 1 through 31
// Week (none implemented)
//'W': weekNumber(),
// Month
'b': lang.shortMonths[month], // Short month, like 'Jan'
'B': lang.months[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
}, Highcharts.dateFormats);
// do the replaces
for (key in replacements) {
while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
}
}
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Format a single variable. Similar to sprintf, without the % prefix.
*/
function formatSingle(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
val = numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
} else {
val = dateFormat(format, val);
}
return val;
}
/**
* Format a string according to a subset of the rules of Python's String.format method.
*/
function format(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while ((index = str.indexOf(splitter)) !== -1) {
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
}
/**
* Get the magnitude of a number
*/
function getMagnitude(num) {
return math.pow(10, mathFloor(math.log(num) / math.LN10));
}
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
* @param {Array} multiples
* @param {Number} magnitude
* @param {Object} options
*/
function normalizeTickInterval(interval, multiples, magnitude, options) {
var normalized, i;
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = pick(magnitude, 1);
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) {
multiples = [1, 2, 2.5, 5, 10];
// the allowDecimals option
if (options && options.allowDecimals === false) {
if (magnitude === 1) {
multiples = [1, 2, 5, 10];
} else if (magnitude <= 0.1) {
multiples = [1 / magnitude];
}
}
}
// normalize the interval to the nearest multiple
for (i = 0; i < multiples.length; i++) {
interval = multiples[i];
if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) {
break;
}
}
// multiply back to the correct magnitude
interval *= magnitude;
return interval;
}
/**
* Get a normalized tick interval for dates. Returns a configuration object with
* unit range (interval), count and name. Used to prepare data for getTimeTicks.
* Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
* of segments in stock charts, the normalizing logic was extracted in order to
* prevent it for running over again for each segment having the same interval.
* #662, #697.
*/
function normalizeTimeTickInterval(tickInterval, unitsOption) {
var units = unitsOption || [[
MILLISECOND, // unit name
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
SECOND,
[1, 2, 5, 10, 15, 30]
], [
MINUTE,
[1, 2, 5, 10, 15, 30]
], [
HOUR,
[1, 2, 3, 4, 6, 8, 12]
], [
DAY,
[1, 2]
], [
WEEK,
[1, 2]
], [
MONTH,
[1, 2, 3, 4, 6]
], [
YEAR,
null
]],
unit = units[units.length - 1], // default unit is years
interval = timeUnits[unit[0]],
multiples = unit[1],
count,
i;
// loop through the units to find the one that best fits the tickInterval
for (i = 0; i < units.length; i++) {
unit = units[i];
interval = timeUnits[unit[0]];
multiples = unit[1];
if (units[i + 1]) {
// lessThan is in the middle between the highest multiple and the next unit.
var lessThan = (interval * multiples[multiples.length - 1] +
timeUnits[units[i + 1][0]]) / 2;
// break and keep the current unit
if (tickInterval <= lessThan) {
break;
}
}
}
// prevent 2.5 years intervals, though 25, 250 etc. are allowed
if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) {
multiples = [1, 2, 5];
}
// get the count
count = normalizeTickInterval(
tickInterval / interval,
multiples,
unit[0] === YEAR ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360
);
return {
unitRange: interval,
count: count,
unitName: unit[0]
};
}
/**
* Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday. Return an array
* with the time positions. Used in datetime axes as well as for grouping
* data on a datetime axis.
*
* @param {Object} normalizedInterval The interval in axis values (ms) and the count
* @param {Number} min The minimum in axis values
* @param {Number} max The maximum in axis values
* @param {Number} startOfWeek
*/
function getTimeTicks(normalizedInterval, min, max, startOfWeek) {
var tickPositions = [],
i,
higherRanks = {},
useUTC = defaultOptions.global.useUTC,
minYear, // used in months and years as a basis for Date.UTC()
minDate = new Date(min),
interval = normalizedInterval.unitRange,
count = normalizedInterval.count;
if (defined(min)) { // #1300
if (interval >= timeUnits[SECOND]) { // second
minDate.setMilliseconds(0);
minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 :
count * mathFloor(minDate.getSeconds() / count));
}
if (interval >= timeUnits[MINUTE]) { // minute
minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 :
count * mathFloor(minDate[getMinutes]() / count));
}
if (interval >= timeUnits[HOUR]) { // hour
minDate[setHours](interval >= timeUnits[DAY] ? 0 :
count * mathFloor(minDate[getHours]() / count));
}
if (interval >= timeUnits[DAY]) { // day
minDate[setDate](interval >= timeUnits[MONTH] ? 1 :
count * mathFloor(minDate[getDate]() / count));
}
if (interval >= timeUnits[MONTH]) { // month
minDate[setMonth](interval >= timeUnits[YEAR] ? 0 :
count * mathFloor(minDate[getMonth]() / count));
minYear = minDate[getFullYear]();
}
if (interval >= timeUnits[YEAR]) { // year
minYear -= minYear % count;
minDate[setFullYear](minYear);
}
// week is a special case that runs outside the hierarchy
if (interval === timeUnits[WEEK]) {
// get start of current week, independent of count
minDate[setDate](minDate[getDate]() - minDate[getDay]() +
pick(startOfWeek, 1));
}
// get tick positions
i = 1;
minYear = minDate[getFullYear]();
var time = minDate.getTime(),
minMonth = minDate[getMonth](),
minDateDate = minDate[getDate](),
timezoneOffset = useUTC ?
0 :
(24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950
// iterate and add tick positions at appropriate values
while (time < max) {
tickPositions.push(time);
// if the interval is years, use Date.UTC to increase years
if (interval === timeUnits[YEAR]) {
time = makeTime(minYear + i * count, 0);
// if the interval is months, use Date.UTC to increase months
} else if (interval === timeUnits[MONTH]) {
time = makeTime(minYear, minMonth + i * count);
// if we're using global time, the interval is not fixed as it jumps
// one hour at the DST crossover
} else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) {
time = makeTime(minYear, minMonth, minDateDate +
i * count * (interval === timeUnits[DAY] ? 1 : 7));
// else, the interval is fixed and we use simple addition
} else {
time += interval * count;
}
i++;
}
// push the last time
tickPositions.push(time);
// mark new days if the time is dividible by day (#1649, #1760)
each(grep(tickPositions, function (time) {
return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset;
}), function (time) {
higherRanks[time] = DAY;
});
}
// record information on the chosen unit - for dynamic label formatter
tickPositions.info = extend(normalizedInterval, {
higherRanks: higherRanks,
totalRange: interval * count
});
return tickPositions;
}
/**
* Helper class that contains variuos counters that are local to the chart.
*/
function ChartCounters() {
this.color = 0;
this.symbol = 0;
}
ChartCounters.prototype = {
/**
* Wraps the color counter if it reaches the specified length.
*/
wrapColor: function (length) {
if (this.color >= length) {
this.color = 0;
}
},
/**
* Wraps the symbol counter if it reaches the specified length.
*/
wrapSymbol: function (length) {
if (this.symbol >= length) {
this.symbol = 0;
}
}
};
/**
* Utility method that sorts an object array and keeping the order of equal items.
* ECMA script standard does not specify the behaviour when items are equal.
*/
function stableSort(arr, sortFunction) {
var length = arr.length,
sortValue,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].ss_i = i; // stable sort index
}
arr.sort(function (a, b) {
sortValue = sortFunction(a, b);
return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].ss_i; // stable sort index
}
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMin(data) {
var i = data.length,
min = data[0];
while (i--) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMax(data) {
var i = data.length,
max = data[0];
while (i--) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
/**
* Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
* It loops all properties and invokes destroy if there is a destroy method. The property is
* then delete'ed.
* @param {Object} The object to destroy properties on
* @param {Object} Exception, do not destroy this property, only delete it.
*/
function destroyObjectProperties(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
}
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
function discardElement(element) {
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = createElement(DIV);
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
}
/**
* Provide error messages for debugging, with links to online explanation
*/
function error(code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw msg;
} else if (win.console) {
console.log(msg);
}
}
/**
* Fix JS round off float errors
* @param {Number} num
*/
function correctFloat(num) {
return parseFloat(
num.toPrecision(14)
);
}
/**
* Set the global animation to either a given value, or fall back to the
* given chart's animation option
* @param {Object} animation
* @param {Object} chart
*/
function setAnimation(animation, chart) {
globalAnimation = pick(animation, chart.animation);
}
/**
* The time unit lookup
*/
/*jslint white: true*/
timeUnits = hash(
MILLISECOND, 1,
SECOND, 1000,
MINUTE, 60000,
HOUR, 3600000,
DAY, 24 * 3600000,
WEEK, 7 * 24 * 3600000,
MONTH, 31 * 24 * 3600000,
YEAR, 31556952000
);
/*jslint white: false*/
/**
* Path interpolation algorithm used across adapters
*/
pathAnim = {
/**
* Prepare start and end values so that the path can be animated one to one
*/
init: function (elem, fromD, toD) {
fromD = fromD || '';
var shift = elem.shift,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
endLength,
slice,
i,
start = fromD.split(' '),
end = [].concat(toD), // copy
startBaseLine,
endBaseLine,
sixify = function (arr) { // in splines make move points have six parameters like bezier curves
i = arr.length;
while (i--) {
if (arr[i] === M) {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
};
if (bezier) {
sixify(start);
sixify(end);
}
// pull out the base lines before padding
if (elem.isArea) {
startBaseLine = start.splice(start.length - 6, 6);
endBaseLine = end.splice(end.length - 6, 6);
}
// if shifting points, prepend a dummy point to the end path
if (shift <= end.length / numParams && start.length === end.length) {
while (shift--) {
end = [].concat(end).splice(0, numParams).concat(end);
}
}
elem.shift = 0; // reset for following animations
// copy and append last point until the length matches the end length
if (start.length) {
endLength = end.length;
while (start.length < endLength) {
//bezier && sixify(start);
slice = [].concat(start).splice(start.length - numParams, numParams);
if (bezier) { // disable first control point
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
start = start.concat(slice);
}
}
if (startBaseLine) { // append the base lines for areas
start = start.concat(startBaseLine);
end = end.concat(endBaseLine);
}
return [start, end];
},
/**
* Interpolate each value of the path and return the array
*/
step: function (start, end, pos, complete) {
var ret = [],
i = start.length,
startVal;
if (pos === 1) { // land on the final path without adjustment points appended in the ends
ret = complete;
} else if (i === end.length && pos < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
pos * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
return ret;
}
};
(function ($) {
/**
* The default HighchartsAdapter for jQuery
*/
win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
/**
* Initialize the adapter by applying some extensions to jQuery
*/
init: function (pathAnim) {
// extend the animate function to allow SVG animations
var Fx = $.fx,
Step = Fx.step,
dSetter,
Tween = $.Tween,
propHooks = Tween && Tween.propHooks,
opacityHook = $.cssHooks.opacity;
/*jslint unparam: true*//* allow unused param x in this function */
$.extend($.easing, {
easeOutQuad: function (x, t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
}
});
/*jslint unparam: false*/
// extend some methods to check for elem.attr, which means it is a Highcharts SVG object
$.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
var obj = Step,
base,
elem;
// Handle different parent objects
if (fn === 'cur') {
obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
} else if (fn === '_default' && Tween) { // jQuery 1.8 model
obj = propHooks[fn];
fn = 'set';
}
// Overwrite the method
base = obj[fn];
if (base) { // step.width and step.height don't exist in jQuery < 1.7
// create the extended function replacement
obj[fn] = function (fx) {
// Fx.prototype.cur does not use fx argument
fx = i ? fx : this;
// Don't run animations on textual properties like align (#1821)
if (fx.prop === 'align') {
return;
}
// shortcut
elem = fx.elem;
// Fx.prototype.cur returns the current value. The other ones are setters
// and returning a value has no effect.
return elem.attr ? // is SVG element wrapper
elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
base.apply(this, arguments); // use jQuery's built-in method
};
}
});
// Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
wrap(opacityHook, 'get', function (proceed, elem, computed) {
return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
});
// Define the setter function for d (path definitions)
dSetter = function (fx) {
var elem = fx.elem,
ends;
// Normally start and end should be set in state == 0, but sometimes,
// for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
// in these cases
if (!fx.started) {
ends = pathAnim.init(elem, elem.d, elem.toD);
fx.start = ends[0];
fx.end = ends[1];
fx.started = true;
}
// interpolate each value of the path
elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
};
// jQuery 1.8 style
if (Tween) {
propHooks.d = {
set: dSetter
};
// pre 1.8
} else {
// animate paths
Step.d = dSetter;
}
/**
* Utility for iterating over an array. Parameters are reversed compared to jQuery.
* @param {Array} arr
* @param {Function} fn
*/
this.each = Array.prototype.forEach ?
function (arr, fn) { // modern browsers
return Array.prototype.forEach.call(arr, fn);
} :
function (arr, fn) { // legacy
var i = 0,
len = arr.length;
for (; i < len; i++) {
if (fn.call(arr[i], arr[i], i, arr) === false) {
return i;
}
}
};
/**
* Register Highcharts as a plugin in the respective framework
*/
$.fn.highcharts = function () {
var constr = 'Chart', // default constructor
args = arguments,
options,
ret,
chart;
if (isString(args[0])) {
constr = args[0];
args = Array.prototype.slice.call(args, 1);
}
options = args[0];
// Create the chart
if (options !== UNDEFINED) {
/*jslint unused:false*/
options.chart = options.chart || {};
options.chart.renderTo = this[0];
chart = new Highcharts[constr](options, args[1]);
ret = this;
/*jslint unused:true*/
}
// When called without parameters or with the return argument, get a predefined chart
if (options === UNDEFINED) {
ret = charts[attr(this[0], 'data-highcharts-chart')];
}
return ret;
};
},
/**
* Downloads a script and executes a callback when done.
* @param {String} scriptLocation
* @param {Function} callback
*/
getScript: $.getScript,
/**
* Return the index of an item in an array, or -1 if not found
*/
inArray: $.inArray,
/**
* A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
* @param {Object} elem The HTML element
* @param {String} method Which method to run on the wrapped element
*/
adapterRun: function (elem, method) {
return $(elem)[method]();
},
/**
* Filter an array
*/
grep: $.grep,
/**
* Map an array
* @param {Array} arr
* @param {Function} fn
*/
map: function (arr, fn) {
//return jQuery.map(arr, fn);
var results = [],
i = 0,
len = arr.length;
for (; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
},
/**
* Get the position of an element relative to the top left of the page
*/
offset: function (el) {
return $(el).offset();
},
/**
* Add an event listener
* @param {Object} el A HTML element or custom object
* @param {String} event The event type
* @param {Function} fn The event handler
*/
addEvent: function (el, event, fn) {
$(el).bind(event, fn);
},
/**
* Remove event added with addEvent
* @param {Object} el The object
* @param {String} eventType The event type. Leave blank to remove all events.
* @param {Function} handler The function to remove
*/
removeEvent: function (el, eventType, handler) {
// workaround for jQuery issue with unbinding custom events:
// http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
if (doc[func] && el && !el[func]) {
el[func] = function () {};
}
$(el).unbind(eventType, handler);
},
/**
* Fire an event on a custom object
* @param {Object} el
* @param {String} type
* @param {Object} eventArguments
* @param {Function} defaultFunction
*/
fireEvent: function (el, type, eventArguments, defaultFunction) {
var event = $.Event(type),
detachedType = 'detached' + type,
defaultPrevented;
// Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts
// never uses these properties, Chrome includes them in the default click event and
// raises the warning when they are copied over in the extend statement below.
//
// To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
// testing if they are there (warning in chrome) the only option is to test if running IE.
if (!isIE && eventArguments) {
delete eventArguments.layerX;
delete eventArguments.layerY;
}
extend(event, eventArguments);
// Prevent jQuery from triggering the object method that is named the
// same as the event. For example, if the event is 'select', jQuery
// attempts calling el.select and it goes into a loop.
if (el[type]) {
el[detachedType] = el[type];
el[type] = null;
}
// Wrap preventDefault and stopPropagation in try/catch blocks in
// order to prevent JS errors when cancelling events on non-DOM
// objects. #615.
/*jslint unparam: true*/
$.each(['preventDefault', 'stopPropagation'], function (i, fn) {
var base = event[fn];
event[fn] = function () {
try {
base.call(event);
} catch (e) {
if (fn === 'preventDefault') {
defaultPrevented = true;
}
}
};
});
/*jslint unparam: false*/
// trigger it
$(el).trigger(event);
// attach the method
if (el[detachedType]) {
el[type] = el[detachedType];
el[detachedType] = null;
}
if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
defaultFunction(event);
}
},
/**
* Extension method needed for MooTools
*/
washMouseEvent: function (e) {
var ret = e.originalEvent || e;
// computed by jQuery, needed by IE8
if (ret.pageX === UNDEFINED) { // #1236
ret.pageX = e.pageX;
ret.pageY = e.pageY;
}
return ret;
},
/**
* Animate a HTML element or SVG element wrapper
* @param {Object} el
* @param {Object} params
* @param {Object} options jQuery-like animation options: duration, easing, callback
*/
animate: function (el, params, options) {
var $el = $(el);
if (!el.style) {
el.style = {}; // #1881
}
if (params.d) {
el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
params.d = 1; // because in jQuery, animating to an array has a different meaning
}
$el.stop();
if (params.opacity !== UNDEFINED && el.attr) {
params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
}
$el.animate(params, options);
},
/**
* Stop running animation
*/
stop: function (el) {
$(el).stop();
}
});
}(win.jQuery));
// check for a custom HighchartsAdapter defined prior to this file
var globalAdapter = win.HighchartsAdapter,
adapter = globalAdapter || {};
// Initialize the adapter
if (globalAdapter) {
globalAdapter.init.call(globalAdapter, pathAnim);
}
// Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
// and all the utility functions will be null. In that case they are populated by the
// default adapters below.
var adapterRun = adapter.adapterRun,
getScript = adapter.getScript,
inArray = adapter.inArray,
each = adapter.each,
grep = adapter.grep,
offset = adapter.offset,
map = adapter.map,
addEvent = adapter.addEvent,
removeEvent = adapter.removeEvent,
fireEvent = adapter.fireEvent,
washMouseEvent = adapter.washMouseEvent,
animate = adapter.animate,
stop = adapter.stop;
/* ****************************************************************************
* Handle the options *
*****************************************************************************/
var
defaultLabelOptions = {
enabled: true,
// rotation: 0,
// align: 'center',
x: 0,
y: 15,
/*formatter: function () {
return this.value;
},*/
style: {
color: '#666',
cursor: 'default',
fontSize: '11px',
lineHeight: '14px'
}
};
defaultOptions = {
colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970',
'#f28f43', '#77a1e5', '#c42525', '#a6c96a'],
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
decimalPoint: '.',
numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ','
},
global: {
useUTC: true,
canvasToolsURL: 'http://code.highcharts.com/stock/1.3.7/modules/canvas-tools.js',
VMLRadialGradientURL: 'http://code.highcharts.com/stock/1.3.7/gfx/vml-radial-gradient.png'
},
chart: {
//animation: true,
//alignTicks: false,
//reflow: true,
//className: null,
//events: { load, selection },
//margin: [null],
//marginTop: null,
//marginRight: null,
//marginBottom: null,
//marginLeft: null,
borderColor: '#4572A7',
//borderWidth: 0,
borderRadius: 5,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
//shadow: false,
spacing: [10, 10, 15, 10],
//spacingTop: 10,
//spacingRight: 10,
//spacingBottom: 15,
//spacingLeft: 10,
style: {
fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
fontSize: '12px'
},
backgroundColor: '#FFFFFF',
//plotBackgroundColor: null,
plotBorderColor: '#C0C0C0',
//plotBorderWidth: 0,
//plotShadow: false,
//zoomType: ''
resetZoomButton: {
theme: {
zIndex: 20
},
position: {
align: 'right',
x: -10,
//verticalAlign: 'top',
y: 10
}
// relativeTo: 'plot'
}
},
title: {
text: 'Chart title',
align: 'center',
// floating: false,
margin: 15,
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#274b6d',//#3E576F',
fontSize: '16px'
}
},
subtitle: {
text: '',
align: 'center',
// floating: false
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#4d759e'
}
},
plotOptions: {
line: { // base series options
allowPointSelect: false,
showCheckbox: false,
animation: {
duration: 1000
},
//connectNulls: false,
//cursor: 'default',
//clip: true,
//dashStyle: null,
//enableMouseTracking: true,
events: {},
//legendIndex: 0,
//linecap: 'round',
lineWidth: 2,
//shadow: false,
// stacking: null,
marker: {
enabled: true,
//symbol: null,
lineWidth: 0,
radius: 4,
lineColor: '#FFFFFF',
//fillColor: null,
states: { // states for a single point
hover: {
enabled: true
//radius: base + 2
},
select: {
fillColor: '#FFFFFF',
lineColor: '#000000',
lineWidth: 2
}
}
},
point: {
events: {}
},
dataLabels: merge(defaultLabelOptions, {
align: 'center',
enabled: false,
formatter: function () {
return this.y === null ? '' : numberFormat(this.y, -1);
},
verticalAlign: 'bottom', // above singular point
y: 0
// backgroundColor: undefined,
// borderColor: undefined,
// borderRadius: undefined,
// borderWidth: undefined,
// padding: 3,
// shadow: false
}),
cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
pointRange: 0,
//pointStart: 0,
//pointInterval: 1,
//showInLegend: null, // auto: true for standalone series, false for linked series
states: { // states for the entire series
hover: {
//enabled: false,
//lineWidth: base + 1,
marker: {
// lineWidth: base + 1,
// radius: base + 1
}
},
select: {
marker: {}
}
},
stickyTracking: true
//tooltip: {
//pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>'
//valueDecimals: null,
//xDateFormat: '%A, %b %e, %Y',
//valuePrefix: '',
//ySuffix: ''
//}
// turboThreshold: 1000
// zIndex: null
}
},
labels: {
//items: [],
style: {
//font: defaultFont,
position: ABSOLUTE,
color: '#3E576F'
}
},
legend: {
enabled: true,
align: 'center',
//floating: false,
layout: 'horizontal',
labelFormatter: function () {
return this.name;
},
borderWidth: 1,
borderColor: '#909090',
borderRadius: 5,
navigation: {
// animation: true,
activeColor: '#274b6d',
// arrowSize: 12
inactiveColor: '#CCC'
// style: {} // text styles
},
// margin: 10,
// reversed: false,
shadow: false,
// backgroundColor: null,
/*style: {
padding: '5px'
},*/
itemStyle: {
cursor: 'pointer',
color: '#274b6d',
fontSize: '12px'
},
itemHoverStyle: {
//cursor: 'pointer', removed as of #601
color: '#000'
},
itemHiddenStyle: {
color: '#CCC'
},
itemCheckboxStyle: {
position: ABSOLUTE,
width: '13px', // for IE precision
height: '13px'
},
// itemWidth: undefined,
symbolWidth: 16,
symbolPadding: 5,
verticalAlign: 'bottom',
// width: undefined,
x: 0,
y: 0,
title: {
//text: null,
style: {
fontWeight: 'bold'
}
}
},
loading: {
// hideDuration: 100,
labelStyle: {
fontWeight: 'bold',
position: RELATIVE,
top: '1em'
},
// showDuration: 0,
style: {
position: ABSOLUTE,
backgroundColor: 'white',
opacity: 0.5,
textAlign: 'center'
}
},
tooltip: {
enabled: true,
animation: hasSVG,
//crosshairs: null,
backgroundColor: 'rgba(255, 255, 255, .85)',
borderWidth: 1,
borderRadius: 3,
dateTimeLabelFormats: {
millisecond: '%A, %b %e, %H:%M:%S.%L',
second: '%A, %b %e, %H:%M:%S',
minute: '%A, %b %e, %H:%M',
hour: '%A, %b %e, %H:%M',
day: '%A, %b %e, %Y',
week: 'Week from %A, %b %e, %Y',
month: '%B %Y',
year: '%Y'
},
//formatter: defaultFormatter,
headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
shadow: true,
//shared: false,
snap: isTouchDevice ? 25 : 10,
style: {
color: '#333333',
cursor: 'default',
fontSize: '12px',
padding: '8px',
whiteSpace: 'nowrap'
}
//xDateFormat: '%A, %b %e, %Y',
//valueDecimals: null,
//valuePrefix: '',
//valueSuffix: ''
},
credits: {
enabled: true,
text: 'Highcharts.com',
href: 'http://www.highcharts.com',
position: {
align: 'right',
x: -10,
verticalAlign: 'bottom',
y: -5
},
style: {
cursor: 'pointer',
color: '#909090',
fontSize: '9px'
}
}
};
// Series defaults
var defaultPlotOptions = defaultOptions.plotOptions,
defaultSeriesOptions = defaultPlotOptions.line;
// set the default time methods
setTimeMethods();
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var useUTC = defaultOptions.global.useUTC,
GET = useUTC ? 'getUTC' : 'get',
SET = useUTC ? 'setUTC' : 'set';
makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) {
return new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
};
getMinutes = GET + 'Minutes';
getHours = GET + 'Hours';
getDay = GET + 'Day';
getDate = GET + 'Date';
getMonth = GET + 'Month';
getFullYear = GET + 'FullYear';
setMinutes = SET + 'Minutes';
setHours = SET + 'Hours';
setDate = SET + 'Date';
setMonth = SET + 'Month';
setFullYear = SET + 'FullYear';
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
function setOptions(options) {
// Pull out axis options and apply them to the respective default axis options
/*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis);
defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis);
options.xAxis = options.yAxis = UNDEFINED;*/
// Merge in the default options
defaultOptions = merge(defaultOptions, options);
// Apply UTC
setTimeMethods();
return defaultOptions;
}
/**
* Get the updated default options. Merely exposing defaultOptions for outside modules
* isn't enough because the setOptions method creates a new object.
*/
function getOptions() {
return defaultOptions;
}
/**
* Handle color operations. The object methods are chainable.
* @param {String} input The input color in either rbga or hex format
*/
var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
var Color = function (input) {
// declare variables
var rgba = [], result, stops;
/**
* Parse the input color to rgba array
* @param {String} input
*/
function init(input) {
// Gradients
if (input && input.stops) {
stops = map(input.stops, function (stop) {
return Color(stop[1]);
});
// Solid colors
} else {
// rgba
result = rgbaRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
} else {
// hex
result = hexRegEx.exec(input);
if (result) {
rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
} else {
// rgb
result = rgbRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}
}
}
}
/**
* Return the color a specified format
* @param {String} format
*/
function get(format) {
var ret;
if (stops) {
ret = merge(input);
ret.stops = [].concat(ret.stops);
each(stops, function (stop, i) {
ret.stops[i] = [ret.stops[i][0], stop.get(format)];
});
// it's NaN if gradient colors on a column chart
} else if (rgba && !isNaN(rgba[0])) {
if (format === 'rgb') {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
} else if (format === 'a') {
ret = rgba[3];
} else {
ret = 'rgba(' + rgba.join(',') + ')';
}
} else {
ret = input;
}
return ret;
}
/**
* Brighten the color
* @param {Number} alpha
*/
function brighten(alpha) {
if (stops) {
each(stops, function (stop) {
stop.brighten(alpha);
});
} else if (isNumber(alpha) && alpha !== 0) {
var i;
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
}
/**
* Set the color's opacity to a given alpha value
* @param {Number} alpha
*/
function setOpacity(alpha) {
rgba[3] = alpha;
return this;
}
// initialize: parse the input
init(input);
// public methods
return {
get: get,
brighten: brighten,
rgba: rgba,
setOpacity: setOpacity
};
};
/**
* A wrapper object for SVG elements
*/
function SVGElement() {}
SVGElement.prototype = {
/**
* Initialize the SVG renderer
* @param {Object} renderer
* @param {String} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(SVG_NS, nodeName);
wrapper.renderer = renderer;
/**
* A collection of attribute setters. These methods, if defined, are called right before a certain
* attribute is set on an element wrapper. Returning false prevents the default attribute
* setter to run. Returning a value causes the default setter to set that value. Used in
* Renderer.label.
*/
wrapper.attrSetters = {};
},
/**
* Default base for animation
*/
opacity: 1,
/**
* Animate a given attribute
* @param {Object} params
* @param {Number} options The same options as in jQuery animation
* @param {Function} complete Function to perform at the end of animation
*/
animate: function (params, options, complete) {
var animOptions = pick(options, globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
animOptions = merge(animOptions);
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params);
if (complete) {
complete();
}
}
},
/**
* Set or get a given attribute
* @param {Object|String} hash
* @param {Mixed|Undefined} val
*/
attr: function (hash, val) {
var wrapper = this,
key,
value,
result,
i,
child,
element = wrapper.element,
nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text"
renderer = wrapper.renderer,
skipAttr,
titleNode,
attrSetters = wrapper.attrSetters,
shadows = wrapper.shadows,
hasSetSymbolSize,
doTransform,
ret = wrapper;
// single key-value pair
if (isString(hash) && defined(val)) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (isString(hash)) {
key = hash;
if (nodeName === 'circle') {
key = { x: 'cx', y: 'cy' }[key] || key;
} else if (key === 'strokeWidth') {
key = 'stroke-width';
}
ret = attr(element, key) || wrapper[key] || 0;
if (key !== 'd' && key !== 'visibility' && key !== 'fill') { // 'd' is string in animation step
ret = parseFloat(ret);
}
// setter
} else {
for (key in hash) {
skipAttr = false; // reset
value = hash[key];
// check for a specific attribute setter
result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
if (result !== false) {
if (result !== UNDEFINED) {
value = result; // the attribute setter has returned a new value to set
}
// paths
if (key === 'd') {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
//wrapper.d = value; // shortcut for animations
// update child tspans x values
} else if (key === 'x' && nodeName === 'text') {
for (i = 0; i < element.childNodes.length; i++) {
child = element.childNodes[i];
// if the x values are equal, the tspan represents a linebreak
if (attr(child, 'x') === attr(element, 'x')) {
//child.setAttribute('x', value);
attr(child, 'x', value);
}
}
} else if (wrapper.rotation && (key === 'x' || key === 'y')) {
doTransform = true;
// apply gradients
} else if (key === 'fill') {
value = renderer.color(value, element, key);
// circle x and y
} else if (nodeName === 'circle' && (key === 'x' || key === 'y')) {
key = { x: 'cx', y: 'cy' }[key] || key;
// rectangle border radius
} else if (nodeName === 'rect' && key === 'r') {
attr(element, {
rx: value,
ry: value
});
skipAttr = true;
// translation and text rotation
} else if (key === 'translateX' || key === 'translateY' || key === 'rotation' ||
key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') {
doTransform = true;
skipAttr = true;
// apply opacity as subnode (required by legacy WebKit and Batik)
} else if (key === 'stroke') {
value = renderer.color(value, element, key);
// emulate VML's dashstyle implementation
} else if (key === 'dashstyle') {
key = 'stroke-dasharray';
value = value && value.toLowerCase();
if (value === 'solid') {
value = NONE;
} else if (value) {
value = value
.replace('shortdashdotdot', '3,1,1,1,1,1,')
.replace('shortdashdot', '3,1,1,1')
.replace('shortdot', '1,1,')
.replace('shortdash', '3,1,')
.replace('longdash', '8,3,')
.replace(/dot/g, '1,3,')
.replace('dash', '4,3,')
.replace(/,$/, '')
.split(','); // ending comma
i = value.length;
while (i--) {
value[i] = pInt(value[i]) * pick(hash['stroke-width'], wrapper['stroke-width']);
}
value = value.join(',');
}
// IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2
// is unable to cast them. Test again with final IE9.
} else if (key === 'width') {
value = pInt(value);
// Text alignment
} else if (key === 'align') {
key = 'text-anchor';
value = { left: 'start', center: 'middle', right: 'end' }[value];
// Title requires a subnode, #431
} else if (key === 'title') {
titleNode = element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(SVG_NS, 'title');
element.appendChild(titleNode);
}
titleNode.textContent = value;
}
// jQuery animate changes case
if (key === 'strokeWidth') {
key = 'stroke-width';
}
// In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke-
// width is 0. #1369
if (key === 'stroke-width' || key === 'stroke') {
wrapper[key] = value;
// Only apply the stroke attribute if the stroke width is defined and larger than 0
if (wrapper.stroke && wrapper['stroke-width']) {
attr(element, 'stroke', wrapper.stroke);
attr(element, 'stroke-width', wrapper['stroke-width']);
wrapper.hasStroke = true;
} else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) {
element.removeAttribute('stroke');
wrapper.hasStroke = false;
}
skipAttr = true;
}
// symbols
if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
if (!hasSetSymbolSize) {
wrapper.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
// let the shadow follow the main element
if (shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
i = shadows.length;
while (i--) {
attr(
shadows[i],
key,
key === 'height' ?
mathMax(value - (shadows[i].cutHeight || 0), 0) :
value
);
}
}
// validate heights
if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) {
value = 0;
}
// Record for animation and quick access without polling the DOM
wrapper[key] = value;
if (key === 'text') {
// Delete bBox memo when the text changes
if (value !== wrapper.textStr) {
delete wrapper.bBox;
}
wrapper.textStr = value;
if (wrapper.added) {
renderer.buildText(wrapper);
}
} else if (!skipAttr) {
attr(element, key, value);
}
}
}
// Update transform. Do this outside the loop to prevent redundant updating for batch setting
// of attributes.
if (doTransform) {
wrapper.updateTransform();
}
}
return ret;
},
/**
* Add a class name to an element
*/
addClass: function (className) {
var element = this.element,
currentClassName = attr(element, 'class') || '';
if (currentClassName.indexOf(className) === -1) {
attr(element, 'class', currentClassName + ' ' + className);
}
return this;
},
/* hasClass and removeClass are not (yet) needed
hasClass: function (className) {
return attr(this.element, 'class').indexOf(className) !== -1;
},
removeClass: function (className) {
attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
return this;
},
*/
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
* @param {Object} hash
*/
symbolAttr: function (hash) {
var wrapper = this;
each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping path to this object
* @param {String} id
*/
clip: function (clipRect) {
return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and return the
* calculated attributes
* @param {Number} strokeWidth
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
crisp: function (strokeWidth, x, y, width, height) {
var wrapper = this,
key,
attribs = {},
values = {},
normalizer;
strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0;
normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
// normalize for crisp edges
values.x = mathFloor(x || wrapper.x || 0) + normalizer;
values.y = mathFloor(y || wrapper.y || 0) + normalizer;
values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer);
values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer);
values.strokeWidth = strokeWidth;
for (key in values) {
if (wrapper[key] !== values[key]) { // only set attribute if changed
wrapper[key] = attribs[key] = values[key];
}
}
return attribs;
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: function (styles) {
/*jslint unparam: true*//* allow unused param a in the regexp function below */
var elemWrapper = this,
elem = elemWrapper.element,
textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width),
n,
serializedCss = '',
hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
/*jslint unparam: false*/
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Merge the new styles with the old ones
styles = extend(
elemWrapper.styles,
styles
);
// store object
elemWrapper.styles = styles;
if (textWidth) {
delete styles.width;
}
// serialize and set style attribute
if (isIE && !hasSVG) {
css(elemWrapper.element, styles);
} else {
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// re-build text
if (textWidth && elemWrapper.added) {
elemWrapper.renderer.buildText(elemWrapper);
}
return elemWrapper;
},
/**
* Add an event listener
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function (e) {
svgElement.touchEventFired = Date.now();
e.preventDefault();
handler.call(element, e);
};
element.onclick = function (e) {
if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* pie slices regardless of positioning inside the chart. The format is
* [centerX, centerY, diameter] in pixels.
*/
setRadialReference: function (coordinates) {
this.element.radialReference = coordinates;
return this;
},
/**
* Move an object and its children by x and y values
* @param {Number} x
* @param {Number} y
*/
translate: function (x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip
*/
invert: function () {
var wrapper = this;
wrapper.inverted = true;
wrapper.updateTransform();
return wrapper;
},
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*/
htmlCss: function (styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets
* @param {Boolean} refresh Whether to force a fresh value from the DOM or to
* use the cached value
*
* @return {Object} A hash containing values for x, y, width and height
*/
htmlGetBBox: function () {
var wrapper = this,
element = wrapper.element,
bBox = wrapper.bBox;
// faking getBBox in exported SVG in legacy IE
if (!bBox) {
// faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
if (element.nodeName === 'text') {
element.style.position = ABSOLUTE;
}
bBox = wrapper.bBox = {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}
return bBox;
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform
*/
htmlUpdateTransform: function () {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this,
renderer = wrapper.renderer,
elem = wrapper.element,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
x = wrapper.x || 0,
y = wrapper.y || 0,
align = wrapper.textAlign || 'left',
alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
nonLeft = align && align !== 'left',
shadows = wrapper.shadows;
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
if (shadows) { // used in labels/tooltip
each(shadows, function (shadow) {
css(shadow, {
marginLeft: translateX + 1,
marginTop: translateY + 1
});
});
}
// apply inversion
if (wrapper.inverted) { // wrapper is a group
each(elem.childNodes, function (child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var width, height,
rotation = wrapper.rotation,
baseline,
radians = 0,
costheta = 1,
sintheta = 0,
quad,
textWidth = pInt(wrapper.textWidth),
xCorr = wrapper.xCorr || 0,
yCorr = wrapper.yCorr || 0,
currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
if (defined(rotation)) {
radians = rotation * deg2rad; // deg to rad
costheta = mathCos(radians);
sintheta = mathSin(radians);
wrapper.setSpanRotation(rotation, sintheta, costheta);
}
width = pick(wrapper.elemWidth, elem.offsetWidth);
height = pick(wrapper.elemHeight, elem.offsetHeight);
// update textWidth
if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
css(elem, {
width: textWidth + PX,
display: 'block',
whiteSpace: 'normal'
});
width = textWidth;
}
// correct x and y
baseline = renderer.fontMetrics(elem.style.fontSize).b;
xCorr = costheta < 0 && -width;
yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
// correct for the length/height of the text
if (nonLeft) {
xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
if (rotation) {
yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
}
css(elem, {
textAlign: align
});
}
// record correction
wrapper.xCorr = xCorr;
wrapper.yCorr = yCorr;
}
// apply position with correction
css(elem, {
left: (x + xCorr) + PX,
top: (y + yCorr) + PX
});
// force reflow in webkit to apply the left and top on useHTML element (#1249)
if (isWebKit) {
height = elem.offsetHeight; // assigned to height for JSLint purpose
}
// record current text transform
wrapper.cTT = currentTextTransform;
}
},
/**
* Set the rotation of an individual HTML span
*/
setSpanRotation: function (rotation) {
var rotationStyle = {},
cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
css(this.element, rotationStyle);
},
/**
* Private method to update the transform attribute based on internal
* properties
*/
updateTransform: function () {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
transform;
// flipping affects translate as adjustment for flipping around the group's axis
if (inverted) {
translateX += wrapper.attr('width');
translateY += wrapper.attr('height');
}
// Apply translate. Nearly all transformed elements have translation, so instead
// of checking for translate = 0, do it always (#1767, #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')');
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
}
if (transform.length) {
attr(wrapper.element, 'transform', transform.join(' '));
}
},
/**
* Bring the element to the front
*/
toFront: function () {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Break down alignment options like align, verticalAlign, x and y
* to x and y relative to the chart.
*
* @param {Object} alignOptions
* @param {Boolean} alignByTranslate
* @param {String[Object} box The box to align to, needs a width and height. When the
* box is a string, it refers to an object in the Renderer. For example, when
* box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
* x and y properties.
*
*/
align: function (alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) { // boxes other than renderer handle this internally
this.alignTo = alignTo = box || 'renderer';
erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right' || align === 'center') {
x += (box.width - (alignOptions.width || 0)) /
{ right: 1, center: 2 }[align];
}
attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
// Vertical align
if (vAlign === 'bottom' || vAlign === 'middle') {
y += (box.height - (alignOptions.height || 0)) /
({ bottom: 1, middle: 2 }[vAlign] || 1);
}
attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element
*/
getBBox: function () {
var wrapper = this,
bBox = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation = wrapper.rotation,
element = wrapper.element,
styles = wrapper.styles,
rad = rotation * deg2rad;
if (!bBox) {
// SVG elements
if (element.namespaceURI === SVG_NS || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change width and height in case
// of rotation (below)
extend({}, element.getBBox()) :
// Canvas renderer and legacy IE in export mode
{
width: element.offsetWidth,
height: element.offsetHeight
};
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The other condition
// is for Opera that returns a width of -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = { width: 0, height: 0 };
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers using the .useHTML option
// need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669)
if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') {
bBox.height = height = 14;
}
// Adjust for rotated text
if (rotation) {
bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
}
}
wrapper.bBox = bBox;
}
return bBox;
},
/**
* Show the element
*/
show: function () {
return this.attr({ visibility: VISIBLE });
},
/**
* Hide the element
*/
hide: function () {
return this.attr({ visibility: HIDDEN });
},
fadeOut: function (duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function () {
elemWrapper.hide();
}
});
},
/**
* Add the element
* @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
* to append the element to the renderer.box.
*/
add: function (parent) {
var renderer = this.renderer,
parentWrapper = parent || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes = parentNode.childNodes,
element = this.element,
zIndex = attr(element, 'zIndex'),
otherElement,
otherZIndex,
i,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// mark the container as having z indexed children
if (zIndex) {
parentWrapper.handleZ = true;
zIndex = pInt(zIndex);
}
// insert according to this and other elements' zIndex
if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
for (i = 0; i < childNodes.length; i++) {
otherElement = childNodes[i];
otherZIndex = attr(otherElement, 'zIndex');
if (otherElement !== element && (
// insert before the first element with a higher zIndex
pInt(otherZIndex) > zIndex ||
// if no zIndex given, insert before the first element with a zIndex
(!defined(zIndex) && defined(otherZIndex))
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
break;
}
}
}
// default: append at the end
if (!inserted) {
parentNode.appendChild(element);
}
// mark as added
this.added = true;
// fire an event for internal hooks
fireEvent(this, 'add');
return this;
},
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper
*/
destroy: function () {
var wrapper = this,
element = wrapper.element || {},
shadows = wrapper.shadows,
parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
grandParent,
key,
i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
// destroy shadows
if (shadows) {
each(shadows, function (shadow) {
wrapper.safeRemoveChild(shadow);
});
}
// In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393).
while (parentToClean && parentToClean.div.childNodes.length === 0) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(wrapper.renderer.alignedObjects, wrapper);
}
for (key in wrapper) {
delete wrapper[key];
}
return null;
},
/**
* Add a shadow to the element. Must be done after the element is added to the DOM
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
shadow,
element = this.element,
strokeWidth,
shadowWidth,
shadowElementOpacity,
// compensate for inverted plot area
transform;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
transform = this.parentInverted ?
'(-1,-1)' :
'(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
for (i = 1; i <= shadowWidth; i++) {
shadow = element.cloneNode(0);
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
attr(shadow, {
'isShadow': 'true',
'stroke': shadowOptions.color || 'black',
'stroke-opacity': shadowElementOpacity * i,
'stroke-width': strokeWidth,
'transform': 'translate' + transform,
'fill': NONE
});
if (cutOff) {
attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
shadow.cutHeight = strokeWidth;
}
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
}
};
/**
* The default SVG renderer
*/
var SVGRenderer = function () {
this.init.apply(this, arguments);
};
SVGRenderer.prototype = {
Element: SVGElement,
/**
* Initialize the SVGRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
* @param {Boolean} forExport
*/
init: function (container, width, height, forExport) {
var renderer = this,
loc = location,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
version: '1.1'
});
element = boxWrapper.element;
container.appendChild(element);
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', SVG_NS);
}
// object properties
renderer.isSVG = true;
renderer.box = element;
renderer.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
// Page url used for internal references. #24, #672, #1070
renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
loc.href
.replace(/#.*?$/, '') // remove the hash
.replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
.replace(/ /g, '%20') : // replace spaces (needed for Safari only)
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
renderer.defs = this.createElement('defs').add();
renderer.forExport = forExport;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position may land
// between pixels. The container itself doesn't display this, but an SVG element
// inside this container will be drawn at subpixel precision. In order to draw
// sharp lines, this must be compensated for. This doesn't seem to work inside
// iframes though (like in jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
renderer.subPixelFix = subPixelFix = function () {
css(container, { left: 0, top: 0 });
rect = container.getBoundingClientRect();
css(container, {
left: (mathCeil(rect.left) - rect.left) + PX,
top: (mathCeil(rect.top) - rect.top) + PX
});
};
// run the fix now
subPixelFix();
// run it on resize
addEvent(win, 'resize', subPixelFix);
}
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none. #608.
*/
isHidden: function () {
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*/
destroy: function () {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler
// We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
// See issue #982
if (renderer.subPixelFix) {
removeEvent(win, 'resize', renderer.subPixelFix);
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element
* @param {Object} nodeName
*/
createElement: function (nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for use in canvas renderer
*/
draw: function () {},
/**
* Parse a simple HTML string into SVG tspans
*
* @param {Object} textNode The parent text SVG node
*/
buildText: function (wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
lines = pick(wrapper.textStr, '').toString()
.replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
.replace(/<(i|em)>/g, '<span style="font-style:italic">')
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g),
childNodes = textNode.childNodes,
styleRegex = /style="([^"]+)"/,
hrefRegex = /href="(http[^"]+)"/,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
i = childNodes.length;
/// remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
if (width && !wrapper.added) {
this.box.appendChild(textNode); // attach it to the DOM to read offset width
}
// remove empty line at end
if (lines[lines.length - 1] === '') {
lines.pop();
}
// build the lines
each(lines, function (line, lineNo) {
var spans, spanNo = 0;
line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
each(spans, function (span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(SVG_NS, 'tspan'),
spanStyle; // #390
if (styleRegex.test(span)) {
spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
attr(tspan, 'style', spanStyle);
}
if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
css(tspan, { cursor: 'pointer' });
}
span = (span.replace(/<(.|\n)*?>/g, '') || ' ')
.replace(/</g, '<')
.replace(/>/g, '>');
// Nested tags aren't supported, and cause crash in Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
if (!spanNo) { // first span in a line, align it to the left
attributes.x = parentX;
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// first span on subsequent line, add the line height
if (!spanNo && lineNo) {
// allow getting the right offset height in exporting in IE
if (!hasSVG && forExport) {
css(tspan, { display: 'block' });
}
// Set the line height based on the font size of either
// the text element or the tspan element
attr(
tspan,
'dy',
textLineHeight || renderer.fontMetrics(
/px$/.test(tspan.style.fontSize) ?
tspan.style.fontSize :
textStyles.fontSize
).h,
// Safari 6.0.2 - too optimized for its own good (#1539)
// TODO: revisit this with future versions of Safari
isWebKit && tspan.offsetHeight
);
}
// Append it
textNode.appendChild(tspan);
spanNo++;
// check width and apply soft breaks
if (width) {
var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
tooLong,
actualWidth,
clipHeight = wrapper._clipHeight,
rest = [],
dy = pInt(textLineHeight || 16),
softLineNo = 1,
bBox;
while (words.length || rest.length) {
delete wrapper.bBox; // delete cache
bBox = wrapper.getBBox();
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!hasSVG && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
}
tooLong = actualWidth > width;
if (!tooLong || words.length === 1) { // new line needed
words = rest;
rest = [];
if (words.length) {
softLineNo++;
if (clipHeight && softLineNo * dy > clipHeight) {
words = ['...'];
wrapper.attr('title', wrapper.textStr);
} else {
tspan = doc.createElementNS(SVG_NS, 'tspan');
attr(tspan, {
dy: dy,
x: parentX
});
if (spanStyle) { // #390
attr(tspan, 'style', spanStyle);
}
textNode.appendChild(tspan);
if (actualWidth > width) { // a single word is pressing it out
width = actualWidth;
}
}
}
} else { // append to existing line tspan
tspan.removeChild(tspan.firstChild);
rest.unshift(words.pop());
}
if (words.length) {
tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
}
}
}
}
}
});
});
},
/**
* Create a button with preset states
* @param {String} text
* @param {Number} x
* @param {Number} y
* @param {Function} callback
* @param {Object} normalState
* @param {Object} hoverState
* @param {Object} pressedState
*/
button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
curState = 0,
stateOptions,
stateStyle,
normalStyle,
hoverStyle,
pressedStyle,
disabledStyle,
STYLE = 'style',
verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
// Normal state - prepare the attributes
normalState = merge({
'stroke-width': 1,
stroke: '#CCCCCC',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FEFEFE'],
[1, '#F6F6F6']
]
},
r: 2,
padding: 5,
style: {
color: 'black'
}
}, normalState);
normalStyle = normalState[STYLE];
delete normalState[STYLE];
// Hover state
hoverState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FFF'],
[1, '#ACF']
]
}
}, hoverState);
hoverStyle = hoverState[STYLE];
delete hoverState[STYLE];
// Pressed state
pressedState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#9BD'],
[1, '#CDF']
]
}
}, pressedState);
pressedStyle = pressedState[STYLE];
delete pressedState[STYLE];
// Disabled state
disabledState = merge(normalState, {
style: {
color: '#CCC'
}
}, disabledState);
disabledStyle = disabledState[STYLE];
delete disabledState[STYLE];
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
if (curState !== 3) {
label.attr(hoverState)
.css(hoverStyle);
}
});
addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
if (curState !== 3) {
stateOptions = [normalState, hoverState, pressedState][curState];
stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
label.attr(stateOptions)
.css(stateStyle);
}
});
label.setState = function (state) {
label.state = curState = state;
if (!state) {
label.attr(normalState)
.css(normalStyle);
} else if (state === 2) {
label.attr(pressedState)
.css(pressedStyle);
} else if (state === 3) {
label.attr(disabledState)
.css(disabledStyle);
}
};
return label
.on('click', function () {
if (curState !== 3) {
callback.call(label);
}
})
.attr(normalState)
.css(extend({ cursor: 'default' }, normalStyle));
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels
* @param {Array} points
* @param {Number} width
*/
crispLine: function (points, width) {
// points format: [M, 0, 0, L, 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave the same.
points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path
* @param {Array} path An SVG path in array form
*/
path: function (path) {
var attr = {
fill: NONE
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
return this.createElement('path').attr(attr);
},
/**
* Draw and return an SVG circle
* @param {Number} x The x position
* @param {Number} y The y position
* @param {Number} r The radius
*/
circle: function (x, y, r) {
var attr = isObject(x) ?
x :
{
x: x,
y: y,
r: r
};
return this.createElement('circle').attr(attr);
},
/**
* Draw and return an arc
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} r Radius
* @param {Number} innerR Inner radius like used in donut charts
* @param {Number} start Starting angle
* @param {Number} end Ending angle
*/
arc: function (x, y, r, innerR, start, end) {
var arc;
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Number} width
* @param {Number} height
* @param {Number} r Border corner radius
* @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
*/
rect: function (x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect').attr({
rx: r,
ry: r,
fill: NONE
});
return wrapper.attr(
isObject(x) ?
x :
// do not crispify when an object is passed in (as in column charts)
wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
);
},
/**
* Resize the box and re-align all aligned elements
* @param {Object} width
* @param {Object} height
* @param {Boolean} animate
*
*/
setSize: function (width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
width: width,
height: height
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create a group
* @param {String} name The group will be given a class name of 'highcharts-{name}'.
* This can be used for styling and scripting.
*/
g: function (name) {
var elem = this.createElement('g');
return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
},
/**
* Display an image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var attribs = {
preserveAspectRatio: NONE
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
*
* @param {Object} symbol
* @param {Object} x
* @param {Object} y
* @param {Object} radius
* @param {Object} options
*/
symbol: function (symbol, x, y, width, height, options) {
var obj,
// get the symbol definition function
symbolFn = this.symbols[symbol],
// check if there's a path defined for this symbol
path = symbolFn && symbolFn(
mathRound(x),
mathRound(y),
width,
height,
options
),
imageElement,
imageRegex = /^url\((.*?)\)$/,
imageSrc,
imageSize,
centerImage;
if (path) {
obj = this.path(path);
// expando properties for use in animate and attr
extend(obj, {
symbolName: symbol,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// image symbols
} else if (imageRegex.test(symbol)) {
// On image load, set the size and position
centerImage = function (img, size) {
if (img.element) { // it may be destroyed in the meantime (#1390)
img.attr({
width: size[0],
height: size[1]
});
if (!img.alignByTranslate) { // #185
img.translate(
mathRound((width - size[0]) / 2), // #1378
mathRound((height - size[1]) / 2)
);
}
}
};
imageSrc = symbol.match(imageRegex)[1];
imageSize = symbolSizes[imageSrc];
// Ireate the image synchronously, add attribs async
obj = this.image(imageSrc)
.attr({
x: x,
y: y
});
obj.isImg = true;
if (imageSize) {
centerImage(obj, imageSize);
} else {
// Initialize image to be 0 size so export will still function if there's no cached sizes.
//
obj.attr({ width: 0, height: 0 });
// Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
// the created element must be assigned to a variable in order to load (#292).
imageElement = createElement('img', {
onload: function () {
centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
},
src: imageSrc
});
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*/
symbols: {
'circle': function (x, y, w, h) {
var cpw = 0.166 * w;
return [
M, x + w / 2, y,
'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
'Z'
];
},
'square': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function (x, y, w, h, options) {
var start = options.start,
radius = options.r || w || h,
end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
innerRadius = options.innerR,
open = options.open,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
longArc = options.end - start < mathPI ? 0 : 1;
return [
M,
x + radius * cosStart,
y + radius * sinStart,
'A', // arcTo
radius, // x radius
radius, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + radius * cosEnd,
y + radius * sinEnd,
open ? M : L,
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart,
open ? '' : 'Z' // close
];
}
},
/**
* Define a clipping rectangle
* @param {String} id
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
var wrapper,
id = PREFIX + idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
return wrapper;
},
/**
* Take a color and return it if it's a string, make it a gradient if it's a
* gradient configuration object. Prior to Highstock, an array was used to define
* a linear gradient with pixel positions relative to the SVG. In newer versions
* we change the coordinates to apply relative to the shape, using coordinates
* 0-1 within the shape. To preserve backwards compatibility, linearGradient
* in this definition is an object of x1, y1, x2 and y2.
*
* @param {Object} color The color or config object
*/
color: function (color, elem, prop) {
var renderer = this,
colorObject,
regexRgba = /^rgba/,
gradName,
gradAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
n,
id,
key = [];
// Apply linear or radial gradients
if (color && color.linearGradient) {
gradName = 'linearGradient';
} else if (color && color.radialGradient) {
gradName = 'radialGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
gradAttr = merge(gradAttr, {
cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2],
gradientUnits: 'userSpaceOnUse'
});
}
// Build the unique key to detect whether we need to create a new element (#1282)
for (n in gradAttr) {
if (n !== 'id') {
key.push(n, gradAttr[n]);
}
}
for (n in stops) {
key.push(stops[n]);
}
key = key.join(',');
// Check if a gradient object with the same config object is created within this renderer
if (gradients[key]) {
id = gradients[key].id;
} else {
// Set the id and create the element
gradAttr.id = id = PREFIX + idCounter++;
gradients[key] = gradientObject = renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(stops, function (stop) {
var stopObject;
if (regexRgba.test(stop[1])) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Return the reference to the gradient object
return 'url(' + renderer.url + '#' + id + ')';
// Webkit and Batik can't show rgba.
} else if (regexRgba.test(color)) {
colorObject = Color(color);
attr(elem, prop + '-opacity', colorObject.get('a'));
return colorObject.get('rgb');
} else {
// Remove the opacity attribute added above. Does not throw if the attribute is not there.
elem.removeAttribute(prop + '-opacity');
return color;
}
},
/**
* Add text to the SVG object
* @param {String} str
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Boolean} useHTML Use HTML to render the text
*/
text: function (str, x, y, useHTML) {
// declare variables
var renderer = this,
defaultChartStyle = defaultOptions.chart.style,
fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
wrapper;
if (useHTML && !renderer.forExport) {
return renderer.html(str, x, y);
}
x = mathRound(pick(x, 0));
y = mathRound(pick(y, 0));
wrapper = renderer.createElement('text')
.attr({
x: x,
y: y,
text: str
})
.css({
fontFamily: defaultChartStyle.fontFamily,
fontSize: defaultChartStyle.fontSize
});
// Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
if (fakeSVG) {
wrapper.css({
position: ABSOLUTE
});
}
wrapper.x = x;
wrapper.y = y;
return wrapper;
},
/**
* Create HTML text node. This is used by the VML renderer as well as the SVG
* renderer through the useHTML option.
*
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
html: function (str, x, y) {
var defaultChartStyle = defaultOptions.chart.style,
wrapper = this.createElement('span'),
attrSetters = wrapper.attrSetters,
element = wrapper.element,
renderer = wrapper.renderer;
// Text setter
attrSetters.text = function (value) {
if (value !== element.innerHTML) {
delete this.bBox;
}
element.innerHTML = value;
return false;
};
// Various setters which rely on update transform
attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) {
if (key === 'align') {
key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
}
wrapper[key] = value;
wrapper.htmlUpdateTransform();
return false;
};
// Set the default attributes
wrapper.attr({
text: str,
x: mathRound(x),
y: mathRound(y)
})
.css({
position: ABSOLUTE,
whiteSpace: 'nowrap',
fontFamily: defaultChartStyle.fontFamily,
fontSize: defaultChartStyle.fontSize
});
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (renderer.isSVG) {
wrapper.add = function (svgGroupWrapper) {
var htmlGroup,
container = renderer.box.parentNode,
parentGroup,
parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent is translated
each(parents.reverse(), function (parentGroup) {
var htmlGroupStyle;
// Create a HTML div and append it to the parent div to emulate
// the SVG group structure
htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
className: attr(parentGroup.element, 'class')
}, {
position: ABSOLUTE,
left: (parentGroup.translateX || 0) + PX,
top: (parentGroup.translateY || 0) + PX
}, htmlGroup || container); // the top group is appended to container
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position whenever the SVG group
// position is changed
extend(parentGroup.attrSetters, {
translateX: function (value) {
htmlGroupStyle.left = value + PX;
},
translateY: function (value) {
htmlGroupStyle.top = value + PX;
},
visibility: function (value, key) {
htmlGroupStyle[key] = value;
}
});
});
}
} else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font size
*/
fontMetrics: function (fontSize) {
fontSize = pInt(fontSize || 11);
// Empirical values found by comparing font size and bounding box height.
// Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2),
baseline = mathRound(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline
};
},
/**
* Add a label, a text item that can hold a colored or gradient background
* as well as a border and shadow.
* @param {string} str
* @param {Number} x
* @param {Number} y
* @param {String} shape
* @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
* coordinates it should be pinned to
* @param {Number} anchorY
* @param {Boolean} baseline Whether to position the label relative to the text baseline,
* like renderer.text, or to the upper border of the rectangle.
* @param {String} className Class name for the group
*/
label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
var renderer = this,
wrapper = renderer.g(className),
text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
//.add(wrapper),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
crispAdjust = 0,
deferredAttr = {},
baselineOffset,
attrSetters = wrapper.attrSetters,
needsBox;
/**
* This function runs after the label is added to the DOM (when the bounding box is
* available), and after the text of the label is updated to detect the new bounding
* box and reflect it in the border box.
*/
function updateBoxSize() {
var boxX,
boxY,
style = text.element.style;
bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) &&
text.getBBox();
wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// update the label-scoped y offset
baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b;
if (needsBox) {
// create the border box if it is not already present
if (!box) {
boxX = mathRound(-alignFactor * padding);
boxY = baseline ? -baselineOffset : 0;
wrapper.box = box = shape ?
renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
box.add(wrapper);
}
// apply the box attributes
if (!box.isImg) { // #1630
box.attr(merge({
width: wrapper.width,
height: wrapper.height
}, deferredAttr));
}
deferredAttr = null;
}
}
/**
* This function runs after setting text or padding, but only if padding is changed
*/
function updateTextPadding() {
var styles = wrapper.styles,
textAlign = styles && styles.textAlign,
x = paddingLeft + padding * (1 - alignFactor),
y;
// determin y based on the baseline
y = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && (textAlign === 'center' || textAlign === 'right')) {
x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
}
// update if anything changed
if (x !== text.x || y !== text.y) {
text.attr({
x: x,
y: y
});
}
// record current values
text.x = x;
text.y = y;
}
/**
* Set a box attribute, or defer it if the box is not yet created
* @param {Object} key
* @param {Object} value
*/
function boxAttr(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
}
function getSizeAfterAdd() {
text.add(wrapper);
wrapper.attr({
text: str, // alignment is available now
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
}
/**
* After the text element is added, get the desired size of the border box
* and add it before the text in the DOM.
*/
addEvent(wrapper, 'add', getSizeAfterAdd);
/*
* Add specific attribute setters.
*/
// only change local variables
attrSetters.width = function (value) {
width = value;
return false;
};
attrSetters.height = function (value) {
height = value;
return false;
};
attrSetters.padding = function (value) {
if (defined(value) && value !== padding) {
padding = value;
updateTextPadding();
}
return false;
};
attrSetters.paddingLeft = function (value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
return false;
};
// change local variable and set attribue as well
attrSetters.align = function (value) {
alignFactor = { left: 0, center: 0.5, right: 1 }[value];
return false; // prevent setting text-anchor on the group
};
// apply these to the box and the text alike
attrSetters.text = function (value, key) {
text.attr(key, value);
updateBoxSize();
updateTextPadding();
return false;
};
// apply these to the box but not to the text
attrSetters[STROKE_WIDTH] = function (value, key) {
needsBox = true;
crispAdjust = value % 2 / 2;
boxAttr(key, value);
return false;
};
attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) {
if (key === 'fill') {
needsBox = true;
}
boxAttr(key, value);
return false;
};
attrSetters.anchorX = function (value, key) {
anchorX = value;
boxAttr(key, value + crispAdjust - wrapperX);
return false;
};
attrSetters.anchorY = function (value, key) {
anchorY = value;
boxAttr(key, value - wrapperY);
return false;
};
// rename attributes
attrSetters.x = function (value) {
wrapper.x = value; // for animation getter
value -= alignFactor * ((width || bBox.width) + padding);
wrapperX = mathRound(value);
wrapper.attr('translateX', wrapperX);
return false;
};
attrSetters.y = function (value) {
wrapperY = wrapper.y = mathRound(value);
wrapper.attr('translateY', wrapperY);
return false;
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
return extend(wrapper, {
/**
* Pick up some properties and apply them to the text instead of the wrapper
*/
css: function (styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) {
if (styles[prop] !== UNDEFINED) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
},
/**
* Return the bounding box of the box, not the group
*/
getBBox: function () {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Apply the shadow to the box
*/
shadow: function (b) {
if (box) {
box.shadow(b);
}
return wrapper;
},
/**
* Destroy and release memory.
*/
destroy: function () {
removeEvent(wrapper, 'add', getSizeAfterAdd);
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null;
}
});
}
}; // end SVGRenderer
// general renderer
Renderer = SVGRenderer;
/* ****************************************************************************
* *
* START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
* For applications and websites that don't need IE support, like platform *
* targeted mobile apps and web apps, this code can be removed. *
* *
*****************************************************************************/
/**
* @constructor
*/
var VMLRenderer, VMLElement;
if (!hasSVG && !useCanVG) {
/**
* The VML element wrapper.
*/
Highcharts.VMLElement = VMLElement = {
/**
* Initialize a new VML element wrapper. It builds the markup as a string
* to minimize DOM traffic.
* @param {Object} renderer
* @param {Object} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this,
markup = ['<', nodeName, ' filled="f" stroked="f"'],
style = ['position: ', ABSOLUTE, ';'],
isDiv = nodeName === DIV;
// divs and shapes need size
if (nodeName === 'shape' || isDiv) {
style.push('left:0;top:0;width:1px;height:1px;');
}
style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
markup.push(' style="', style.join(''), '"/>');
// create element with default attributes and style
if (nodeName) {
markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
markup.join('')
: renderer.prepVML(markup);
wrapper.element = createElement(markup);
}
wrapper.renderer = renderer;
wrapper.attrSetters = {};
},
/**
* Add the node to the given parent
* @param {Object} parent
*/
add: function (parent) {
var wrapper = this,
renderer = wrapper.renderer,
element = wrapper.element,
box = renderer.box,
inverted = parent && parent.inverted,
// get the parent node
parentNode = parent ?
parent.element || parent :
box;
// if the parent group is inverted, apply inversion on all children
if (inverted) { // only on groups
renderer.invertChild(element, parentNode);
}
// append it
parentNode.appendChild(element);
// align text after adding to be able to read offset
wrapper.added = true;
if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
wrapper.updateTransform();
}
// fire an event for internal hooks
fireEvent(wrapper, 'add');
return wrapper;
},
/**
* VML always uses htmlUpdateTransform
*/
updateTransform: SVGElement.prototype.htmlUpdateTransform,
/**
* Set the rotation of a span with oldIE's filter
*/
setSpanRotation: function (rotation, sintheta, costheta) {
// Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
// but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
// has support for CSS3 transform. The getBBox method also needs to be updated
// to compensate for the rotation, like it currently does for SVG.
// Test case: http://highcharts.com/tests/?file=text-rotation
css(this.element, {
filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
', sizingMethod=\'auto expand\')'].join('') : NONE
});
},
/**
* Converts a subset of an SVG path definition to its VML counterpart. Takes an array
* as the parameter and returns a string.
*/
pathToVML: function (value) {
// convert paths
var i = value.length,
path = [],
clockwise;
while (i--) {
// Multiply by 10 to allow subpixel precision.
// Substracting half a pixel seems to make the coordinates
// align with SVG, but this hasn't been tested thoroughly
if (isNumber(value[i])) {
path[i] = mathRound(value[i] * 10) - 5;
} else if (value[i] === 'Z') { // close the path
path[i] = 'x';
} else {
path[i] = value[i];
// When the start X and end X coordinates of an arc are too close,
// they are rounded to the same value above. In this case, substract 1 from the end X
// position. #760, #1371.
if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
clockwise = value[i] === 'wa' ? 1 : -1; // #1642
if (path[i + 5] === path[i + 7]) {
path[i + 7] -= clockwise;
}
// Start and end Y (#1410)
if (path[i + 6] === path[i + 8]) {
path[i + 8] -= clockwise;
}
}
}
}
// Loop up again to handle path shortcuts (#2132)
/*while (i++ < path.length) {
if (path[i] === 'H') { // horizontal line to
path[i] = 'L';
path.splice(i + 2, 0, path[i - 1]);
} else if (path[i] === 'V') { // vertical line to
path[i] = 'L';
path.splice(i + 1, 0, path[i - 2]);
}
}*/
return path.join(' ') || 'x';
},
/**
* Get or set attributes
*/
attr: function (hash, val) {
var wrapper = this,
key,
value,
i,
result,
element = wrapper.element || {},
elemStyle = element.style,
nodeName = element.nodeName,
renderer = wrapper.renderer,
symbolName = wrapper.symbolName,
hasSetSymbolSize,
shadows = wrapper.shadows,
skipAttr,
attrSetters = wrapper.attrSetters,
ret = wrapper;
// single key-value pair
if (isString(hash) && defined(val)) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter, val is undefined
if (isString(hash)) {
key = hash;
if (key === 'strokeWidth' || key === 'stroke-width') {
ret = wrapper.strokeweight;
} else {
ret = wrapper[key];
}
// setter
} else {
for (key in hash) {
value = hash[key];
skipAttr = false;
// check for a specific attribute setter
result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
if (result !== false && value !== null) { // #620
if (result !== UNDEFINED) {
value = result; // the attribute setter has returned a new value to set
}
// prepare paths
// symbols
if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) {
// if one of the symbol size affecting parameters are changed,
// check all the others only once for each call to an element's
// .attr() method
if (!hasSetSymbolSize) {
wrapper.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
} else if (key === 'd') {
value = value || [];
wrapper.d = value.join(' '); // used in getter for animation
element.path = value = wrapper.pathToVML(value);
// update shadows
if (shadows) {
i = shadows.length;
while (i--) {
shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
}
}
skipAttr = true;
// handle visibility
} else if (key === 'visibility') {
// let the shadow follow the main element
if (shadows) {
i = shadows.length;
while (i--) {
shadows[i].style[key] = value;
}
}
// Instead of toggling the visibility CSS property, move the div out of the viewport.
// This works around #61 and #586
if (nodeName === 'DIV') {
value = value === HIDDEN ? '-999em' : 0;
// In order to redraw, IE7 needs the div to be visible when tucked away
// outside the viewport. So the visibility is actually opposite of
// the expected value. This applies to the tooltip only.
if (!docMode8) {
elemStyle[key] = value ? VISIBLE : HIDDEN;
}
key = 'top';
}
elemStyle[key] = value;
skipAttr = true;
// directly mapped to css
} else if (key === 'zIndex') {
if (value) {
elemStyle[key] = value;
}
skipAttr = true;
// x, y, width, height
} else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) {
wrapper[key] = value; // used in getter
if (key === 'x' || key === 'y') {
key = { x: 'left', y: 'top' }[key];
} else {
value = mathMax(0, value); // don't set width or height below zero (#311)
}
// clipping rectangle special
if (wrapper.updateClipping) {
wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
wrapper.updateClipping();
} else {
// normal
elemStyle[key] = value;
}
skipAttr = true;
// class name
} else if (key === 'class' && nodeName === 'DIV') {
// IE8 Standards mode has problems retrieving the className
element.className = value;
// stroke
} else if (key === 'stroke') {
value = renderer.color(value, element, key);
key = 'strokecolor';
// stroke width
} else if (key === 'stroke-width' || key === 'strokeWidth') {
element.stroked = value ? true : false;
key = 'strokeweight';
wrapper[key] = value; // used in getter, issue #113
if (isNumber(value)) {
value += PX;
}
// dashStyle
} else if (key === 'dashstyle') {
var strokeElem = element.getElementsByTagName('stroke')[0] ||
createElement(renderer.prepVML(['<stroke/>']), null, null, element);
strokeElem[key] = value || 'solid';
wrapper.dashstyle = value; /* because changing stroke-width will change the dash length
and cause an epileptic effect */
skipAttr = true;
// fill
} else if (key === 'fill') {
if (nodeName === 'SPAN') { // text color
elemStyle.color = value;
} else if (nodeName !== 'IMG') { // #1336
element.filled = value !== NONE ? true : false;
value = renderer.color(value, element, key, wrapper);
key = 'fillcolor';
}
// opacity: don't bother - animation is too slow and filters introduce artifacts
} else if (key === 'opacity') {
/*css(element, {
opacity: value
});*/
skipAttr = true;
// rotation on VML elements
} else if (nodeName === 'shape' && key === 'rotation') {
wrapper[key] = element.style[key] = value; // style is for #1873
// Correction for the 1x1 size of the shape container. Used in gauge needles.
element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
element.style.top = mathRound(mathCos(value * deg2rad)) + PX;
// translation for animation
} else if (key === 'translateX' || key === 'translateY' || key === 'rotation') {
wrapper[key] = value;
wrapper.updateTransform();
skipAttr = true;
// text for rotated and non-rotated elements
} else if (key === 'text') {
this.bBox = null;
element.innerHTML = value;
skipAttr = true;
}
if (!skipAttr) {
if (docMode8) { // IE8 setAttribute bug
element[key] = value;
} else {
attr(element, key, value);
}
}
}
}
}
return ret;
},
/**
* Set the element's clipping to a predefined rectangle
*
* @param {String} id The id of the clip rectangle
*/
clip: function (clipRect) {
var wrapper = this,
clipMembers,
cssRet;
if (clipRect) {
clipMembers = clipRect.members;
erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
clipMembers.push(wrapper);
wrapper.destroyClip = function () {
erase(clipMembers, wrapper);
};
cssRet = clipRect.getCSS(wrapper);
} else {
if (wrapper.destroyClip) {
wrapper.destroyClip();
}
cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
}
return wrapper.css(cssRet);
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: SVGElement.prototype.htmlCss,
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
// discardElement will detach the node from its parent before attaching it
// to the garbage bin. Therefore it is important that the node is attached and have parent.
if (element.parentNode) {
discardElement(element);
}
},
/**
* Extend element.destroy by removing it from the clip members array
*/
destroy: function () {
if (this.destroyClip) {
this.destroyClip();
}
return SVGElement.prototype.destroy.apply(this);
},
/**
* Add an event listener. VML override for normalizing event parameters.
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
// simplest possible event model for internal use
this.element['on' + eventType] = function () {
var evt = win.event;
evt.target = evt.srcElement;
handler(evt);
};
return this;
},
/**
* In stacked columns, cut off the shadows so that they don't overlap
*/
cutOffPath: function (path, length) {
var len;
path = path.split(/[ ,]/);
len = path.length;
if (len === 9 || len === 11) {
path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
}
return path.join(' ');
},
/**
* Apply a drop shadow by copying elements and giving them different strokes
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
element = this.element,
renderer = this.renderer,
shadow,
elemStyle = element.style,
markup,
path = element.path,
strokeWidth,
modifiedPath,
shadowWidth,
shadowElementOpacity;
// some times empty paths are not strings
if (path && typeof path.value !== 'string') {
path = 'x';
}
modifiedPath = path;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
for (i = 1; i <= 3; i++) {
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
// Cut off shadows for stacked column items
if (cutOff) {
modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
}
markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
'" filled="false" path="', modifiedPath,
'" coordsize="10 10" style="', element.style.cssText, '" />'];
shadow = createElement(renderer.prepVML(markup),
null, {
left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
}
);
if (cutOff) {
shadow.cutOff = strokeWidth + 1;
}
// apply the opacity
markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
createElement(renderer.prepVML(markup), null, null, shadow);
// insert it
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
// record it
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
}
};
VMLElement = extendClass(SVGElement, VMLElement);
/**
* The VML renderer
*/
var VMLRendererExtension = { // inherit SVGRenderer
Element: VMLElement,
isIE8: userAgent.indexOf('MSIE 8.0') > -1,
/**
* Initialize the VMLRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
*/
init: function (container, width, height) {
var renderer = this,
boxWrapper,
box,
css;
renderer.alignedObjects = [];
boxWrapper = renderer.createElement(DIV);
box = boxWrapper.element;
box.style.position = RELATIVE; // for freeform drawing using renderer directly
container.appendChild(boxWrapper.element);
// generate the containing box
renderer.isVML = true;
renderer.box = box;
renderer.boxWrapper = boxWrapper;
renderer.setSize(width, height, false);
// The only way to make IE6 and IE7 print is to use a global namespace. However,
// with IE8 the only way to make the dynamic shapes visible in screen and print mode
// seems to be to add the xmlns attribute and the behaviour style inline.
if (!doc.namespaces.hcv) {
doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
// Setup default CSS (#2153, #2368, #2384)
css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
'{ behavior:url(#default#VML); display: inline-block; } ';
try {
doc.createStyleSheet().cssText = css;
} catch (e) {
doc.styleSheets[0].cssText += css;
}
}
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none
*/
isHidden: function () {
return !this.box.offsetWidth;
},
/**
* Define a clipping rectangle. In VML it is accomplished by storing the values
* for setting the CSS style to all associated members.
*
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
// create a dummy element
var clipRect = this.createElement(),
isObj = isObject(x);
// mimic a rectangle with its style object for automatic updating in attr
return extend(clipRect, {
members: [],
left: (isObj ? x.x : x) + 1,
top: (isObj ? x.y : y) + 1,
width: (isObj ? x.width : width) - 1,
height: (isObj ? x.height : height) - 1,
getCSS: function (wrapper) {
var element = wrapper.element,
nodeName = element.nodeName,
isShape = nodeName === 'shape',
inverted = wrapper.inverted,
rect = this,
top = rect.top - (isShape ? element.offsetTop : 0),
left = rect.left,
right = left + rect.width,
bottom = top + rect.height,
ret = {
clip: 'rect(' +
mathRound(inverted ? left : top) + 'px,' +
mathRound(inverted ? bottom : right) + 'px,' +
mathRound(inverted ? right : bottom) + 'px,' +
mathRound(inverted ? top : left) + 'px)'
};
// issue 74 workaround
if (!inverted && docMode8 && nodeName === 'DIV') {
extend(ret, {
width: right + PX,
height: bottom + PX
});
}
return ret;
},
// used in attr and animation to update the clipping of all members
updateClipping: function () {
each(clipRect.members, function (member) {
member.css(clipRect.getCSS(member));
});
}
});
},
/**
* Take a color and return it if it's a string, make it a gradient if it's a
* gradient configuration object, and apply opacity.
*
* @param {Object} color The color or config object
*/
color: function (color, elem, prop, wrapper) {
var renderer = this,
colorObject,
regexRgba = /^rgba/,
markup,
fillType,
ret = NONE;
// Check for linear or radial gradient
if (color && color.linearGradient) {
fillType = 'gradient';
} else if (color && color.radialGradient) {
fillType = 'pattern';
}
if (fillType) {
var stopColor,
stopOpacity,
gradient = color.linearGradient || color.radialGradient,
x1,
y1,
x2,
y2,
opacity1,
opacity2,
color1,
color2,
fillAttr = '',
stops = color.stops,
firstStop,
lastStop,
colors = [],
addFillNode = function () {
// Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
'" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
createElement(renderer.prepVML(markup), null, null, elem);
};
// Extend from 0 to 1
firstStop = stops[0];
lastStop = stops[stops.length - 1];
if (firstStop[0] > 0) {
stops.unshift([
0,
firstStop[1]
]);
}
if (lastStop[0] < 1) {
stops.push([
1,
lastStop[1]
]);
}
// Compute the stops
each(stops, function (stop, i) {
if (regexRgba.test(stop[1])) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
// Build the color attribute
colors.push((stop[0] * 100) + '% ' + stopColor);
// Only start and end opacities are allowed, so we use the first and the last
if (!i) {
opacity1 = stopOpacity;
color2 = stopColor;
} else {
opacity2 = stopOpacity;
color1 = stopColor;
}
});
// Apply the gradient to fills only.
if (prop === 'fill') {
// Handle linear gradient angle
if (fillType === 'gradient') {
x1 = gradient.x1 || gradient[0] || 0;
y1 = gradient.y1 || gradient[1] || 0;
x2 = gradient.x2 || gradient[2] || 0;
y2 = gradient.y2 || gradient[3] || 0;
fillAttr = 'angle="' + (90 - math.atan(
(y2 - y1) / // y vector
(x2 - x1) // x vector
) * 180 / mathPI) + '"';
addFillNode();
// Radial (circular) gradient
} else {
var r = gradient.r,
sizex = r * 2,
sizey = r * 2,
cx = gradient.cx,
cy = gradient.cy,
radialReference = elem.radialReference,
bBox,
applyRadialGradient = function () {
if (radialReference) {
bBox = wrapper.getBBox();
cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
sizex *= radialReference[2] / bBox.width;
sizey *= radialReference[2] / bBox.height;
}
fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
'size="' + sizex + ',' + sizey + '" ' +
'origin="0.5,0.5" ' +
'position="' + cx + ',' + cy + '" ' +
'color2="' + color2 + '" ';
addFillNode();
};
// Apply radial gradient
if (wrapper.added) {
applyRadialGradient();
} else {
// We need to know the bounding box to get the size and position right
addEvent(wrapper, 'add', applyRadialGradient);
}
// The fill element's color attribute is broken in IE8 standards mode, so we
// need to set the parent shape's fillcolor attribute instead.
ret = color1;
}
// Gradients are not supported for VML stroke, return the first color. #722.
} else {
ret = stopColor;
}
// if the color is an rgba color, split it and add a fill node
// to hold the opacity component
} else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
colorObject = Color(color);
markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
createElement(this.prepVML(markup), null, null, elem);
ret = colorObject.get('rgb');
} else {
var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
if (propNodes.length) {
propNodes[0].opacity = 1;
propNodes[0].type = 'solid';
}
ret = color;
}
return ret;
},
/**
* Take a VML string and prepare it for either IE8 or IE6/IE7.
* @param {Array} markup A string array of the VML markup to prepare
*/
prepVML: function (markup) {
var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
isIE8 = this.isIE8;
markup = markup.join('');
if (isIE8) { // add xmlns and style inline
markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
if (markup.indexOf('style="') === -1) {
markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
} else {
markup = markup.replace('style="', 'style="' + vmlStyle);
}
} else { // add namespace
markup = markup.replace('<', '<hcv:');
}
return markup;
},
/**
* Create rotated and aligned text
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
text: SVGRenderer.prototype.html,
/**
* Create and return a path element
* @param {Array} path
*/
path: function (path) {
var attr = {
// subpixel precision down to 0.1 (width and height = 1px)
coordsize: '10 10'
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
// create the shape
return this.createElement('shape').attr(attr);
},
/**
* Create and return a circle element. In VML circles are implemented as
* shapes, which is faster than v:oval
* @param {Number} x
* @param {Number} y
* @param {Number} r
*/
circle: function (x, y, r) {
var circle = this.symbol('circle');
if (isObject(x)) {
r = x.r;
y = x.y;
x = x.x;
}
circle.isCircle = true; // Causes x and y to mean center (#1682)
circle.r = r;
return circle.attr({ x: x, y: y });
},
/**
* Create a group using an outer div and an inner v:group to allow rotating
* and flipping. A simple v:group would have problems with positioning
* child HTML elements and CSS clip.
*
* @param {String} name The name of the group
*/
g: function (name) {
var wrapper,
attribs;
// set the class name
if (name) {
attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
}
// the div to hold HTML and clipping
wrapper = this.createElement(DIV).attr(attribs);
return wrapper;
},
/**
* VML override to create a regular HTML image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var obj = this.createElement('img')
.attr({ src: src });
if (arguments.length > 1) {
obj.attr({
x: x,
y: y,
width: width,
height: height
});
}
return obj;
},
/**
* VML uses a shape for rect to overcome bugs and rotation problems
*/
rect: function (x, y, width, height, r, strokeWidth) {
var wrapper = this.symbol('rect');
wrapper.r = isObject(x) ? x.r : r;
//return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)));
return wrapper.attr(
isObject(x) ?
x :
// do not crispify when an object is passed in (as in column charts)
wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
);
},
/**
* In the VML renderer, each child of an inverted div (group) is inverted
* @param {Object} element
* @param {Object} parentNode
*/
invertChild: function (element, parentNode) {
var parentStyle = parentNode.style;
css(element, {
flip: 'x',
left: pInt(parentStyle.width) - 1,
top: pInt(parentStyle.height) - 1,
rotation: -90
});
},
/**
* Symbol definitions that override the parent SVG renderer's symbols
*
*/
symbols: {
// VML specific arc function
arc: function (x, y, w, h, options) {
var start = options.start,
end = options.end,
radius = options.r || w || h,
innerRadius = options.innerR,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
ret;
if (end - start === 0) { // no angle, don't show it.
return ['x'];
}
ret = [
'wa', // clockwise arc to
x - radius, // left
y - radius, // top
x + radius, // right
y + radius, // bottom
x + radius * cosStart, // start x
y + radius * sinStart, // start y
x + radius * cosEnd, // end x
y + radius * sinEnd // end y
];
if (options.open && !innerRadius) {
ret.push(
'e',
M,
x,// - innerRadius,
y// - innerRadius
);
}
ret.push(
'at', // anti clockwise arc to
x - innerRadius, // left
y - innerRadius, // top
x + innerRadius, // right
y + innerRadius, // bottom
x + innerRadius * cosEnd, // start x
y + innerRadius * sinEnd, // start y
x + innerRadius * cosStart, // end x
y + innerRadius * sinStart, // end y
'x', // finish path
'e' // close
);
ret.isArc = true;
return ret;
},
// Add circle symbol path. This performs significantly faster than v:oval.
circle: function (x, y, w, h, wrapper) {
if (wrapper) {
w = h = 2 * wrapper.r;
}
// Center correction, #1682
if (wrapper && wrapper.isCircle) {
x -= w / 2;
y -= h / 2;
}
// Return the path
return [
'wa', // clockwisearcto
x, // left
y, // top
x + w, // right
y + h, // bottom
x + w, // start x
y + h / 2, // start y
x + w, // end x
y + h / 2, // end y
//'x', // finish path
'e' // close
];
},
/**
* Add rectangle symbol path which eases rotation and omits arcsize problems
* compared to the built-in VML roundrect shape
*
* @param {Number} left Left position
* @param {Number} top Top position
* @param {Number} r Border radius
* @param {Object} options Width and height
*/
rect: function (left, top, width, height, options) {
var right = left + width,
bottom = top + height,
ret,
r;
// No radius, return the more lightweight square
if (!defined(options) || !options.r) {
ret = SVGRenderer.prototype.symbols.square.apply(0, arguments);
// Has radius add arcs for the corners
} else {
r = mathMin(options.r, width, height);
ret = [
M,
left + r, top,
L,
right - r, top,
'wa',
right - 2 * r, top,
right, top + 2 * r,
right - r, top,
right, top + r,
L,
right, bottom - r,
'wa',
right - 2 * r, bottom - 2 * r,
right, bottom,
right, bottom - r,
right - r, bottom,
L,
left + r, bottom,
'wa',
left, bottom - 2 * r,
left + 2 * r, bottom,
left + r, bottom,
left, bottom - r,
L,
left, top + r,
'wa',
left, top,
left + 2 * r, top + 2 * r,
left, top + r,
left + r, top,
'x',
'e'
];
}
return ret;
}
}
};
Highcharts.VMLRenderer = VMLRenderer = function () {
this.init.apply(this, arguments);
};
VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
// general renderer
Renderer = VMLRenderer;
}
// This method is used with exporting in old IE, when emulating SVG (see #2314)
SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
var measuringSpan = doc.createElement('span'),
textNode = doc.createTextNode(text);
measuringSpan.appendChild(textNode);
css(measuringSpan, styles);
this.box.appendChild(measuringSpan);
return measuringSpan.offsetWidth;
};
/* ****************************************************************************
* *
* END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
*****************************************************************************/
/* ****************************************************************************
* *
* START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
* TARGETING THAT SYSTEM. *
* *
*****************************************************************************/
var CanVGRenderer,
CanVGController;
if (useCanVG) {
/**
* The CanVGRenderer is empty from start to keep the source footprint small.
* When requested, the CanVGController downloads the rest of the source packaged
* together with the canvg library.
*/
Highcharts.CanVGRenderer = CanVGRenderer = function () {
// Override the global SVG namespace to fake SVG/HTML that accepts CSS
SVG_NS = 'http://www.w3.org/1999/xhtml';
};
/**
* Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
* the implementation from SvgRenderer will not be merged in until first render.
*/
CanVGRenderer.prototype.symbols = {};
/**
* Handles on demand download of canvg rendering support.
*/
CanVGController = (function () {
// List of renderering calls
var deferredRenderCalls = [];
/**
* When downloaded, we are ready to draw deferred charts.
*/
function drawDeferred() {
var callLength = deferredRenderCalls.length,
callIndex;
// Draw all pending render calls
for (callIndex = 0; callIndex < callLength; callIndex++) {
deferredRenderCalls[callIndex]();
}
// Clear the list
deferredRenderCalls = [];
}
return {
push: function (func, scriptLocation) {
// Only get the script once
if (deferredRenderCalls.length === 0) {
getScript(scriptLocation, drawDeferred);
}
// Register render call
deferredRenderCalls.push(func);
}
};
}());
Renderer = CanVGRenderer;
} // end CanVGRenderer
/* ****************************************************************************
* *
* END OF ANDROID < 3 SPECIFIC CODE *
* *
*****************************************************************************/
/**
* The Tick class
*/
function Tick(axis, pos, type, noLabel) {
this.axis = axis;
this.pos = pos;
this.type = type || '';
this.isNew = true;
if (!type && !noLabel) {
this.addLabel();
}
}
Tick.prototype = {
/**
* Write the tick label
*/
addLabel: function () {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
horiz = axis.horiz,
categories = axis.categories,
names = axis.names,
pos = tick.pos,
labelOptions = options.labels,
str,
tickPositions = axis.tickPositions,
width = (horiz && categories &&
!labelOptions.step && !labelOptions.staggerLines &&
!labelOptions.rotation &&
chart.plotWidth / tickPositions.length) ||
(!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931
isFirst = pos === tickPositions[0],
isLast = pos === tickPositions[tickPositions.length - 1],
css,
attr,
value = categories ?
pick(categories[pos], names[pos], pos) :
pos,
label = tick.label,
tickPositionInfo = tickPositions.info,
dateTimeLabelFormat;
// Set the datetime label format. If a higher rank is set for this position, use that. If not,
// use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
}
// set properties for access in render method
tick.isFirst = isFirst;
tick.isLast = isLast;
// get the string
str = axis.labelFormatter.call({
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
value: axis.isLog ? correctFloat(lin2log(value)) : value
});
// prepare CSS
css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
css = extend(css, labelOptions.style);
// first call
if (!defined(label)) {
attr = {
align: axis.labelAlign
};
if (isNumber(labelOptions.rotation)) {
attr.rotation = labelOptions.rotation;
}
if (width && labelOptions.ellipsis) {
attr._clipHeight = axis.len / tickPositions.length;
}
tick.label =
defined(str) && labelOptions.enabled ?
chart.renderer.text(
str,
0,
0,
labelOptions.useHTML
)
.attr(attr)
// without position absolute, IE export sometimes is wrong
.css(css)
.add(axis.labelGroup) :
null;
// update
} else if (label) {
label.attr({
text: str
})
.css(css);
}
},
/**
* Get the offset height or width of the label
*/
getLabelSize: function () {
var label = this.label,
axis = this.axis;
return label ?
((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] :
0;
},
/**
* Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision
* detection with overflow logic.
*/
getLabelSides: function () {
var bBox = this.labelBBox, // assume getLabelSize has run at this point
axis = this.axis,
options = axis.options,
labelOptions = options.labels,
width = bBox.width,
leftSide = width * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] - labelOptions.x;
return [-leftSide, width - leftSide];
},
/**
* Handle the label overflow by adjusting the labels to the left and right edge, or
* hide them if they collide into the neighbour label.
*/
handleOverflow: function (index, xy) {
var show = true,
axis = this.axis,
chart = axis.chart,
isFirst = this.isFirst,
isLast = this.isLast,
x = xy.x,
reversed = axis.reversed,
tickPositions = axis.tickPositions;
if (isFirst || isLast) {
var sides = this.getLabelSides(),
leftSide = sides[0],
rightSide = sides[1],
plotLeft = chart.plotLeft,
plotRight = plotLeft + axis.len,
neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]],
neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1];
if ((isFirst && !reversed) || (isLast && reversed)) {
// Is the label spilling out to the left of the plot area?
if (x + leftSide < plotLeft) {
// Align it to plot left
x = plotLeft - leftSide;
// Hide it if it now overlaps the neighbour label
if (neighbour && x + rightSide > neighbourEdge) {
show = false;
}
}
} else {
// Is the label spilling out to the right of the plot area?
if (x + rightSide > plotRight) {
// Align it to plot right
x = plotRight - rightSide;
// Hide it if it now overlaps the neighbour label
if (neighbour && x + leftSide < neighbourEdge) {
show = false;
}
}
}
// Set the modified x position of the label
xy.x = x;
}
return show;
},
/**
* Get the x and y position for ticks and labels
*/
getPosition: function (horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
},
/**
* Get the x, y position of the tick label
*/
getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis,
transA = axis.transA,
reversed = axis.reversed,
staggerLines = axis.staggerLines,
baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b,
rotation = labelOptions.rotation;
x = x + labelOptions.x - (tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
y = y + labelOptions.y - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for rotation (#1764)
if (rotation && axis.side === 2) {
y -= baseline - baseline * mathCos(rotation * deg2rad);
}
// Vertically centered
if (!defined(labelOptions.y) && !rotation) { // #1951
y += baseline - label.getBBox().height / 2;
}
// Correct for staggered labels
if (staggerLines) {
y += (index / (step || 1) % staggerLines) * (axis.labelOffset / staggerLines);
}
return {
x: x,
y: y
};
},
/**
* Extendible method to return the path of the marker
*/
getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
M,
x,
y,
L,
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
},
/**
* Put everything in place
*
* @param index {Number}
* @param old {Boolean} Use old coordinates to prepare an animation into new position
*/
render: function (index, old, opacity) {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
renderer = chart.renderer,
horiz = axis.horiz,
type = tick.type,
label = tick.label,
pos = tick.pos,
labelOptions = options.labels,
gridLine = tick.gridLine,
gridPrefix = type ? type + 'Grid' : 'grid',
tickPrefix = type ? type + 'Tick' : 'tick',
gridLineWidth = options[gridPrefix + 'LineWidth'],
gridLineColor = options[gridPrefix + 'LineColor'],
dashStyle = options[gridPrefix + 'LineDashStyle'],
tickLength = options[tickPrefix + 'Length'],
tickWidth = options[tickPrefix + 'Width'] || 0,
tickColor = options[tickPrefix + 'Color'],
tickPosition = options[tickPrefix + 'Position'],
gridLinePath,
mark = tick.mark,
markPath,
step = labelOptions.step,
attribs,
show = true,
tickmarkOffset = axis.tickmarkOffset,
xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
x = xy.x,
y = xy.y,
reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1, // #1480, #1687
staggerLines = axis.staggerLines;
this.isActive = true;
// create the grid line
if (gridLineWidth) {
gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
if (gridLine === UNDEFINED) {
attribs = {
stroke: gridLineColor,
'stroke-width': gridLineWidth
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
if (!type) {
attribs.zIndex = 1;
}
if (old) {
attribs.opacity = 0;
}
tick.gridLine = gridLine =
gridLineWidth ?
renderer.path(gridLinePath)
.attr(attribs).add(axis.gridGroup) :
null;
}
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (!old && gridLine && gridLinePath) {
gridLine[tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
// create the tick mark
if (tickWidth && tickLength) {
// negate the length
if (tickPosition === 'inside') {
tickLength = -tickLength;
}
if (axis.opposite) {
tickLength = -tickLength;
}
markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
if (mark) { // updating
mark.animate({
d: markPath,
opacity: opacity
});
} else { // first time
tick.mark = renderer.path(
markPath
).attr({
stroke: tickColor,
'stroke-width': tickWidth,
opacity: opacity
}).add(axis.axisGroup);
}
}
// the label is created on init - now move it into place
if (label && !isNaN(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and last, it is
// a single centered tick, in which case we show the label anyway (#2100).
if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
(tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
} else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) {
show = false;
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && !isNaN(xy.y)) {
xy.opacity = opacity;
label[tick.isNew ? 'attr' : 'animate'](xy);
tick.isNew = false;
} else {
label.attr('y', -9999); // #1338
}
}
},
/**
* Destructor for the tick prototype
*/
destroy: function () {
destroyObjectProperties(this, this.axis);
}
};
/**
* The object wrapper for plot lines and plot bands
* @param {Object} options
*/
function PlotLineOrBand(axis, options) {
this.axis = axis;
if (options) {
this.options = options;
this.id = options.id;
}
}
PlotLineOrBand.prototype = {
/**
* Render the plot line or plot band. If it is already existing,
* move it.
*/
render: function () {
var plotLine = this,
axis = plotLine.axis,
horiz = axis.horiz,
halfPointRange = (axis.pointRange || 0) / 2,
options = plotLine.options,
optionsLabel = options.label,
label = plotLine.label,
width = options.width,
to = options.to,
from = options.from,
isBand = defined(from) && defined(to),
value = options.value,
dashStyle = options.dashStyle,
svgElem = plotLine.svgElem,
path = [],
addEvent,
eventType,
xs,
ys,
x,
y,
color = options.color,
zIndex = options.zIndex,
events = options.events,
attribs,
renderer = axis.chart.renderer;
// logarithmic conversion
if (axis.isLog) {
from = log2lin(from);
to = log2lin(to);
value = log2lin(value);
}
// plot line
if (width) {
path = axis.getPlotLinePath(value, width);
attribs = {
stroke: color,
'stroke-width': width
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
} else if (isBand) { // plot band
// keep within plot area
from = mathMax(from, axis.min - halfPointRange);
to = mathMin(to, axis.max + halfPointRange);
path = axis.getPlotBandPath(from, to, options);
attribs = {
fill: color
};
if (options.borderWidth) {
attribs.stroke = options.borderColor;
attribs['stroke-width'] = options.borderWidth;
}
} else {
return;
}
// zIndex
if (defined(zIndex)) {
attribs.zIndex = zIndex;
}
// common for lines and bands
if (svgElem) {
if (path) {
svgElem.animate({
d: path
}, null, svgElem.onGetPath);
} else {
svgElem.hide();
svgElem.onGetPath = function () {
svgElem.show();
};
if (label) {
plotLine.label = label = label.destroy();
}
}
} else if (path && path.length) {
plotLine.svgElem = svgElem = renderer.path(path)
.attr(attribs).add();
// events
if (events) {
addEvent = function (eventType) {
svgElem.on(eventType, function (e) {
events[eventType].apply(plotLine, [e]);
});
};
for (eventType in events) {
addEvent(eventType);
}
}
}
// the plot band/line label
if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
// apply defaults
optionsLabel = merge({
align: horiz && isBand && 'center',
x: horiz ? !isBand && 4 : 10,
verticalAlign : !horiz && isBand && 'middle',
y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
rotation: horiz && !isBand && 90
}, optionsLabel);
// add the SVG element
if (!label) {
plotLine.label = label = renderer.text(
optionsLabel.text,
0,
0,
optionsLabel.useHTML
)
.attr({
align: optionsLabel.textAlign || optionsLabel.align,
rotation: optionsLabel.rotation,
zIndex: zIndex
})
.css(optionsLabel.style)
.add();
}
// get the bounding box and align the label
xs = [path[1], path[4], pick(path[6], path[1])];
ys = [path[2], path[5], pick(path[7], path[2])];
x = arrayMin(xs);
y = arrayMin(ys);
label.align(optionsLabel, false, {
x: x,
y: y,
width: arrayMax(xs) - x,
height: arrayMax(ys) - y
});
label.show();
} else if (label) { // move out of sight
label.hide();
}
// chainable
return plotLine;
},
/**
* Remove the plot line or band
*/
destroy: function () {
// remove it from the lookup
erase(this.axis.plotLinesAndBands, this);
delete this.axis;
destroyObjectProperties(this);
}
};
/**
* The class for stack items
*/
function StackItem(axis, options, isNegative, x, stackOption, stacking) {
var inverted = axis.chart.inverted;
this.axis = axis;
// Tells if the stack is negative
this.isNegative = isNegative;
// Save the options to be able to style the label
this.options = options;
// Save the x value to be able to position the label later
this.x = x;
// Initialize total value
this.total = null;
// This will keep each points' extremes stored by series.index
this.points = {};
// Save the stack option on the series configuration object, and whether to treat it as percent
this.stack = stackOption;
this.percent = stacking === 'percent';
// The align options and text align varies on whether the stack is negative and
// if the chart is inverted or not.
// First test the user supplied value, then use the dynamic.
this.alignOptions = {
align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
};
this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
}
StackItem.prototype = {
destroy: function () {
destroyObjectProperties(this, this.axis);
},
/**
* Renders the stack total label and adds it to the stack label group.
*/
render: function (group) {
var options = this.options,
formatOption = options.format,
str = formatOption ?
format(formatOption, this) :
options.formatter.call(this); // format the text in the label
// Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
if (this.label) {
this.label.attr({text: str, visibility: HIDDEN});
// Create new label
} else {
this.label =
this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
.css(options.style) // apply style
.attr({
align: this.textAlign, // fix the text-anchor
rotation: options.rotation, // rotation
visibility: HIDDEN // hidden until setOffset is called
})
.add(group); // add to the labels-group
}
},
/**
* Sets the offset that the stack has from the x value and repositions the label.
*/
setOffset: function (xOffset, xWidth) {
var stackItem = this,
axis = stackItem.axis,
chart = axis.chart,
inverted = chart.inverted,
neg = this.isNegative, // special treatment is needed for negative stacks
y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
yZero = axis.translate(0), // stack origin
h = mathAbs(y - yZero), // stack height
x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
plotHeight = chart.plotHeight,
stackBox = { // this is the box for the complete stack
x: inverted ? (neg ? y : y - h) : x,
y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
width: inverted ? h : xWidth,
height: inverted ? xWidth : h
},
label = this.label,
alignAttr;
if (label) {
label.align(this.alignOptions, null, stackBox); // align the label to the box
// Set visibility (#678)
alignAttr = label.alignAttr;
label.attr({
visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ?
(hasSVG ? 'inherit' : VISIBLE) :
HIDDEN
});
}
}
};
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
function Axis() {
this.init.apply(this, arguments);
}
Axis.prototype = {
/**
* Default options for the X axis - the Y axis has extended defaults
*/
defaultOptions: {
// allowDecimals: null,
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
gridLineColor: '#C0C0C0',
// gridLineDashStyle: 'solid',
// gridLineWidth: 0,
// reversed: false,
labels: defaultLabelOptions,
// { step: null },
lineColor: '#C0D0E0',
lineWidth: 1,
//linkedTo: null,
//max: undefined,
//min: undefined,
minPadding: 0.01,
maxPadding: 0.01,
//minRange: null,
minorGridLineColor: '#E0E0E0',
// minorGridLineDashStyle: null,
minorGridLineWidth: 1,
minorTickColor: '#A0A0A0',
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
//minorTickWidth: 0,
//opposite: false,
//offset: 0,
//plotBands: [{
// events: {},
// zIndex: 1,
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//plotLines: [{
// events: {}
// dashStyle: {}
// zIndex:
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//reversed: false,
// showFirstLabel: true,
// showLastLabel: true,
startOfWeek: 1,
startOnTick: false,
tickColor: '#C0D0E0',
//tickInterval: null,
tickLength: 5,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
tickWidth: 1,
title: {
//text: null,
align: 'middle', // low, middle or high
//margin: 0 for horizontal, 10 for vertical axes,
//rotation: 0,
//side: 'outside',
style: {
color: '#4d759e',
//font: defaultFont.replace('normal', 'bold')
fontWeight: 'bold'
}
//x: 0,
//y: 0
},
type: 'linear' // linear, logarithmic or datetime
},
/**
* This options set extends the defaultOptions for Y axes
*/
defaultYAxisOptions: {
endOnTick: true,
gridLineWidth: 1,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
x: -8,
y: 3
},
lineWidth: 0,
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
tickWidth: 0,
title: {
rotation: 270,
text: 'Values'
},
stackLabels: {
enabled: false,
//align: dynamic,
//y: dynamic,
//x: dynamic,
//verticalAlign: dynamic,
//textAlign: dynamic,
//rotation: 0,
formatter: function () {
return numberFormat(this.total, -1);
},
style: defaultLabelOptions.style
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultLeftAxisOptions: {
labels: {
x: -8,
y: null
},
title: {
rotation: 270
}
},
/**
* These options extend the defaultOptions for right axes
*/
defaultRightAxisOptions: {
labels: {
x: 8,
y: null
},
title: {
rotation: 90
}
},
/**
* These options extend the defaultOptions for bottom axes
*/
defaultBottomAxisOptions: {
labels: {
x: 0,
y: 14
// overflow: undefined,
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultTopAxisOptions: {
labels: {
x: 0,
y: -5
// overflow: undefined
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* Initialize the axis
*/
init: function (chart, userOptions) {
var isXAxis = userOptions.isX,
axis = this;
// Flag, is the axis horizontal
axis.horiz = chart.inverted ? !isXAxis : isXAxis;
// Flag, isXAxis
axis.isXAxis = isXAxis;
axis.xOrY = isXAxis ? 'x' : 'y';
axis.opposite = userOptions.opposite; // needed in setOptions
axis.side = axis.horiz ?
(axis.opposite ? 0 : 2) : // top : bottom
(axis.opposite ? 1 : 3); // right : left
axis.setOptions(userOptions);
var options = this.options,
type = options.type,
isDatetimeAxis = type === 'datetime';
axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
// Flag, stagger lines or not
axis.userOptions = userOptions;
//axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
axis.minPixelPadding = 0;
//axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
//axis.ignoreMaxPadding = UNDEFINED;
axis.chart = chart;
axis.reversed = options.reversed;
axis.zoomEnabled = options.zoomEnabled !== false;
// Initial categories
axis.categories = options.categories || type === 'category';
axis.names = [];
// Elements
//axis.axisGroup = UNDEFINED;
//axis.gridGroup = UNDEFINED;
//axis.axisTitle = UNDEFINED;
//axis.axisLine = UNDEFINED;
// Shorthand types
axis.isLog = type === 'logarithmic';
axis.isDatetimeAxis = isDatetimeAxis;
// Flag, if axis is linked to another axis
axis.isLinked = defined(options.linkedTo);
// Linked axis.
//axis.linkedParent = UNDEFINED;
// Tick positions
//axis.tickPositions = UNDEFINED; // array containing predefined positions
// Tick intervals
//axis.tickInterval = UNDEFINED;
//axis.minorTickInterval = UNDEFINED;
axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0;
// Major ticks
axis.ticks = {};
// Minor ticks
axis.minorTicks = {};
//axis.tickAmount = UNDEFINED;
// List of plotLines/Bands
axis.plotLinesAndBands = [];
// Alternate bands
axis.alternateBands = {};
// Axis metrics
//axis.left = UNDEFINED;
//axis.top = UNDEFINED;
//axis.width = UNDEFINED;
//axis.height = UNDEFINED;
//axis.bottom = UNDEFINED;
//axis.right = UNDEFINED;
//axis.transA = UNDEFINED;
//axis.transB = UNDEFINED;
//axis.oldTransA = UNDEFINED;
axis.len = 0;
//axis.oldMin = UNDEFINED;
//axis.oldMax = UNDEFINED;
//axis.oldUserMin = UNDEFINED;
//axis.oldUserMax = UNDEFINED;
//axis.oldAxisLength = UNDEFINED;
axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
axis.range = options.range;
axis.offset = options.offset || 0;
// Dictionary for stacks
axis.stacks = {};
axis.oldStacks = {};
// Dictionary for stacks max values
axis.stackExtremes = {};
// Min and max in the data
//axis.dataMin = UNDEFINED,
//axis.dataMax = UNDEFINED,
// The axis range
axis.max = null;
axis.min = null;
// User set min and max
//axis.userMin = UNDEFINED,
//axis.userMax = UNDEFINED,
// Run Axis
var eventType,
events = axis.options.events;
// Register
if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
chart.axes.push(axis);
chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis);
}
axis.series = axis.series || []; // populated by Series
// inverted charts have reversed xAxes as default
if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
axis.reversed = true;
}
axis.removePlotBand = axis.removePlotBandOrLine;
axis.removePlotLine = axis.removePlotBandOrLine;
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// extend logarithmic axis
if (axis.isLog) {
axis.val2lin = log2lin;
axis.lin2val = lin2log;
}
},
/**
* Merge and set options
*/
setOptions: function (userOptions) {
this.options = merge(
this.defaultOptions,
this.isXAxis ? {} : this.defaultYAxisOptions,
[this.defaultTopAxisOptions, this.defaultRightAxisOptions,
this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
merge(
defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053)
userOptions
)
);
},
/**
* Update the axis with a new options structure
*/
update: function (newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this._addedPlotLB = this.userMin = this.userMax = UNDEFINED; // #1611, #2306
this.init(chart, extend(newOptions, { events: UNDEFINED }));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Remove the axis from the chart
*/
remove: function (redraw) {
var chart = this.chart,
key = this.xOrY + 'Axis'; // xAxis or yAxis
// Remove associated series
each(this.series, function (series) {
series.remove(false);
});
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function (axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* The default label formatter. The context is a special config object for the label.
*/
defaultLabelFormatter: function () {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === UNDEFINED) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
ret = numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === UNDEFINED) {
if (value >= 1000) { // add thousands separators
ret = numberFormat(value, 0);
} else { // small numbers
ret = numberFormat(value, -1);
}
}
return ret;
},
/**
* Get the minimum and maximum for the series of each axis
*/
getSeriesExtremes: function () {
var axis = this,
chart = axis.chart;
axis.hasVisibleSeries = false;
// reset dataMin and dataMax in case we're redrawing
axis.dataMin = axis.dataMax = null;
// reset cached stacking extremes
axis.stackExtremes = {};
axis.buildStacks();
// loop through this axis' series
each(axis.series, function (series) {
if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
var seriesOptions = series.options,
xData,
threshold = seriesOptions.threshold,
seriesDataMin,
seriesDataMax;
axis.hasVisibleSeries = true;
// Validate threshold in logarithmic axes
if (axis.isLog && threshold <= 0) {
threshold = null;
}
// Get dataMin and dataMax for X axes
if (axis.isXAxis) {
xData = series.xData;
if (xData.length) {
axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
}
// Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
} else {
// Get this particular series extremes
series.getExtremes();
seriesDataMax = series.dataMax;
seriesDataMin = series.dataMin;
// Get the dataMin and dataMax so far. If percentage is used, the min and max are
// always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
// doesn't have active y data, we continue with nulls
if (defined(seriesDataMin) && defined(seriesDataMax)) {
axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
}
// Adjust to threshold
if (defined(threshold)) {
if (axis.dataMin >= threshold) {
axis.dataMin = threshold;
axis.ignoreMinPadding = true;
} else if (axis.dataMax < threshold) {
axis.dataMax = threshold;
axis.ignoreMaxPadding = true;
}
}
}
}
});
},
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this,
axisLength = axis.len,
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axisLength;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * axisLength;
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (postTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (postTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
},
/**
* Utility method to translate an axis value to pixel position.
* @param {Number} value A value in terms of axis units
* @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
* or just the axis/pane itself.
*/
toPixels: function (value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
},
/*
* Utility method to translate a pixel position in to an axis value
* @param {Number} pixel The pixel value coordinate
* @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
* axis/pane itself.
*/
toValue: function (pixel, paneCoordinates) {
return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
},
/**
* Create the path for a plot line that goes from the given value on
* this axis, across the plot to the opposite side
* @param {Number} value
* @param {Number} lineWidth Used for calculation crisp line
* @param {Number] old Use old coordinates (for resizing and rescaling)
*/
getPlotLinePath: function (value, lineWidth, old, force) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
translatedValue = axis.translate(value, null, null, old),
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB;
x1 = x2 = mathRound(translatedValue + transB);
y1 = y2 = mathRound(cHeight - translatedValue - transB);
if (isNaN(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
if (x1 < axisLeft || x1 > axisLeft + axis.width) {
skip = true;
}
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
if (y1 < axisTop || y1 > axisTop + axis.height) {
skip = true;
}
}
return skip && !force ?
null :
chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0);
},
/**
* Create the path for a plot band
*/
getPlotBandPath: function (from, to) {
var toPath = this.getPlotLinePath(to),
path = this.getPlotLinePath(from);
if (path && toPath) {
path.push(
toPath[4],
toPath[5],
toPath[1],
toPath[2]
);
} else { // outside the axis area
path = null;
}
return path;
},
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
getLinearTickPositions: function (tickInterval, min, max) {
var pos,
lastPos,
roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
tickPositions = [];
// Populate the intermediate values
pos = roundedMin;
while (pos <= roundedMax) {
// Place the tick on the rounded value
tickPositions.push(pos);
// Always add the raw tickInterval, not the corrected one.
pos = correctFloat(pos + tickInterval);
// If the interval is not big enough in the current min - max range to actually increase
// the loop variable, we need to break out to prevent endless loop. Issue #619
if (pos === lastPos) {
break;
}
// Record the last value
lastPos = pos;
}
return tickPositions;
},
/**
* Set the tick positions of a logarithmic axis
*/
getLogTickPositions: function (interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = mathRound(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = mathFloor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max)) { // #1670
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
},
/**
* Return the minor tick positions. For logarithmic axes, reuse the same logic
* as for major ticks.
*/
getMinorTickPositions: function () {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
len;
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
getTimeTicks(
normalizeTimeTickInterval(minorTickInterval),
axis.min,
axis.max,
options.startOfWeek
)
);
if (minorTickPositions[0] < axis.min) {
minorTickPositions.shift();
}
} else {
for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
return minorTickPositions;
},
/**
* Adjust the min and max for the minimum range. Keep in mind that the series data is
* not yet processed, so we don't have information on data cropping and grouping, or
* updated axis.pointRange or series.pointRange. The data can't be processed until
* we have finally established min and max.
*/
adjustForMinRange: function () {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function (series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === UNDEFINED || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
var minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
},
/**
* Update translation information
*/
setAxisTranslation: function (saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
transA = axis.transA;
// adjust translation for padding
if (axis.isXAxis) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
each(axis.series, function (series) {
var seriesPointRange = series.pointRange,
pointPlacement = series.options.pointPlacement,
seriesClosestPointRange = series.closestPointRange;
if (seriesPointRange > range) { // #1446
seriesPointRange = 0;
}
pointRange = mathMax(pointRange, seriesPointRange);
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = mathMax(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = mathMax(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
// Set the closestPointRange
if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
closestPointRange = defined(closestPointRange) ?
mathMin(closestPointRange, seriesClosestPointRange) :
seriesClosestPointRange;
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = mathMin(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
axis.closestPointRange = closestPointRange;
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
},
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
setTickPositions: function (secondPass) {
var axis = this,
chart = axis.chart,
options = axis.options,
isLog = axis.isLog,
isDatetimeAxis = axis.isDatetimeAxis,
isXAxis = axis.isXAxis,
isLinked = axis.isLinked,
tickPositioner = axis.options.tickPositioner,
maxPadding = options.maxPadding,
minPadding = options.minPadding,
length,
linkedParentExtremes,
tickIntervalOption = options.tickInterval,
minTickIntervalOption = options.minTickInterval,
tickPixelIntervalOption = options.tickPixelInterval,
tickPositions,
keepTwoTicksOnly,
categories = axis.categories;
// linked axis gets the extremes from the parent axis
if (isLinked) {
axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo];
linkedParentExtremes = axis.linkedParent.getExtremes();
axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
if (options.type !== axis.linkedParent.options.type) {
error(11, 1); // Can't link axes of different type
}
} else { // initial min and max from the extreme data values
axis.min = pick(axis.userMin, options.min, axis.dataMin);
axis.max = pick(axis.userMax, options.max, axis.dataMax);
}
if (isLog) {
if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
error(10, 1); // Can't plot negative values on log axis
}
axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
axis.max = correctFloat(log2lin(axis.max));
}
// handle zoomed range
if (axis.range) {
axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
axis.userMax = axis.max;
if (secondPass) {
axis.range = null; // don't use it when running setExtremes
}
}
// Hook for adjusting this.min and this.max. Used by bubble series.
if (axis.beforePadding) {
axis.beforePadding();
}
// adjust min and max for the minimum range
axis.adjustForMinRange();
// Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
// into account, we do this after computing tick interval (#1337).
if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
length = axis.max - axis.min;
if (length) {
if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
axis.min -= length * minPadding;
}
if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
axis.max += length * maxPadding;
}
}
}
// get tickInterval
if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
axis.tickInterval = 1;
} else if (isLinked && !tickIntervalOption &&
tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
axis.tickInterval = axis.linkedParent.tickInterval;
} else {
axis.tickInterval = pick(
tickIntervalOption,
categories ? // for categoried axis, 1 is default, for linear axis use tickPix
1 :
// don't let it be more than the data range
(axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
);
// For squished axes, set only two ticks
if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial) {
keepTwoTicksOnly = true;
axis.tickInterval /= 4; // tick extremes closer to the real values
}
}
// Now we're finished detecting min and max, crop and group series data. This
// is in turn needed in order to find tick positions in ordinal axes.
if (isXAxis && !secondPass) {
each(axis.series, function (series) {
series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
});
}
// set the translation factor used in translate function
axis.setAxisTranslation(true);
// hook for ordinal axes and radial axes
if (axis.beforeSetTickPositions) {
axis.beforeSetTickPositions();
}
// hook for extensions, used in Highstock ordinal axes
if (axis.postProcessTickInterval) {
axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
}
// In column-like charts, don't cramp in more ticks than there are points (#1943)
if (axis.pointRange) {
axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
}
// Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) {
axis.tickInterval = minTickIntervalOption;
}
// for linear axes, get magnitude and normalize the interval
if (!isDatetimeAxis && !isLog) { // linear
if (!tickIntervalOption) {
axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options);
}
}
// get minorTickInterval
axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ?
axis.tickInterval / 5 : options.minorTickInterval;
// find the tick positions
axis.tickPositions = tickPositions = options.tickPositions ?
[].concat(options.tickPositions) : // Work on a copy (#1565)
(tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max]));
if (!tickPositions) {
// Too many ticks
if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) {
error(19, true);
}
if (isDatetimeAxis) {
tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)(
normalizeTimeTickInterval(axis.tickInterval, options.units),
axis.min,
axis.max,
options.startOfWeek,
axis.ordinalPositions,
axis.closestPointRange,
true
);
} else if (isLog) {
tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max);
} else {
tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max);
}
if (keepTwoTicksOnly) {
tickPositions.splice(1, tickPositions.length - 2);
}
axis.tickPositions = tickPositions;
}
if (!isLinked) {
// reset min/max or remove extremes based on start/end on tick
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1],
minPointOffset = axis.minPointOffset || 0,
singlePad;
if (options.startOnTick) {
axis.min = roundedMin;
} else if (axis.min - minPointOffset > roundedMin) {
tickPositions.shift();
}
if (options.endOnTick) {
axis.max = roundedMax;
} else if (axis.max + minPointOffset < roundedMax) {
tickPositions.pop();
}
// When there is only one point, or all points have the same value on this axis, then min
// and max are equal and tickPositions.length is 1. In this case, add some padding
// in order to center the point, but leave it with one tick. #1337.
if (tickPositions.length === 1) {
singlePad = 0.001; // The lowest possible number to avoid extra padding on columns
axis.min -= singlePad;
axis.max += singlePad;
}
}
},
/**
* Set the max ticks of either the x and y axis collection
*/
setMaxTicks: function () {
var chart = this.chart,
maxTicks = chart.maxTicks || {},
tickPositions = this.tickPositions,
key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-');
if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
maxTicks[key] = tickPositions.length;
}
chart.maxTicks = maxTicks;
},
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
adjustTickAmount: function () {
var axis = this,
chart = axis.chart,
key = axis._maxTicksKey,
tickPositions = axis.tickPositions,
maxTicks = chart.maxTicks;
if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale
var oldTickAmount = axis.tickAmount,
calculatedTickAmount = tickPositions.length,
tickAmount;
// set the axis-level tickAmount to use below
axis.tickAmount = tickAmount = maxTicks[key];
if (calculatedTickAmount < tickAmount) {
while (tickPositions.length < tickAmount) {
tickPositions.push(correctFloat(
tickPositions[tickPositions.length - 1] + axis.tickInterval
));
}
axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1);
axis.max = tickPositions[tickPositions.length - 1];
}
if (defined(oldTickAmount) && tickAmount !== oldTickAmount) {
axis.isDirty = true;
}
}
},
/**
* Set the scale based on data min and max, user set min and max or options
*
*/
setScale: function () {
var axis = this,
stacks = axis.stacks,
type,
i,
isDirtyData,
isDirtyAxisLength;
axis.oldMin = axis.min;
axis.oldMax = axis.max;
axis.oldAxisLength = axis.len;
// set the new axisLength
axis.setAxisSize();
//axisLength = horiz ? axisWidth : axisHeight;
isDirtyAxisLength = axis.len !== axis.oldAxisLength;
// is there new data?
each(axis.series, function (series) {
if (series.isDirtyData || series.isDirty ||
series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
isDirtyData = true;
}
});
// do we really need to go through all this?
if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
// reset stacks
if (!axis.isXAxis) {
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].total = null;
stacks[type][i].cum = 0;
}
}
}
axis.forceRedraw = false;
// get data extremes if needed
axis.getSeriesExtremes();
// get fixed positions based on tickInterval
axis.setTickPositions();
// record old values to decide whether a rescale is necessary later on (#540)
axis.oldUserMin = axis.userMin;
axis.oldUserMax = axis.userMax;
// Mark as dirty if it is not already set to dirty and extremes have changed. #595.
if (!axis.isDirty) {
axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
}
} else if (!axis.isXAxis) {
if (axis.oldStacks) {
stacks = axis.stacks = axis.oldStacks;
}
// reset stacks
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].cum = stacks[type][i].total;
}
}
}
// Set the maximum tick amount
axis.setMaxTicks();
},
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
* @param {Object} eventArguments
*
*/
setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
var axis = this,
chart = axis.chart;
redraw = pick(redraw, true); // defaults to true
// Extend the arguments with min and max
eventArguments = extend(eventArguments, {
min: newMin,
max: newMax
});
// Fire the event
fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
axis.userMin = newMin;
axis.userMax = newMax;
axis.eventArgs = eventArguments;
// Mark for running afterSetExtremes
axis.isDirtyExtremes = true;
// redraw
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Overridable method for zooming chart. Pulled out in a separate method to allow overriding
* in stock charts.
*/
zoom: function (newMin, newMax) {
// Prevent pinch zooming out of range. Check for defined is for #1946.
if (!this.allowZoomOutside) {
if (defined(this.dataMin) && newMin <= this.dataMin) {
newMin = UNDEFINED;
}
if (defined(this.dataMax) && newMax >= this.dataMax) {
newMax = UNDEFINED;
}
}
// In full view, displaying the reset zoom button is not required
this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
// Do it
this.setExtremes(
newMin,
newMax,
false,
UNDEFINED,
{ trigger: 'zoom' }
);
return true;
},
/**
* Update the axis metrics
*/
setAxisSize: function () {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width,
height,
top,
left;
// Expose basic values to use in Series object and navigator
this.left = left = pick(options.left, chart.plotLeft + offsetLeft);
this.top = top = pick(options.top, chart.plotTop);
this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight);
this.height = height = pick(options.height, chart.plotHeight);
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
},
/**
* Get the actual axis extremes
*/
getExtremes: function () {
var axis = this,
isLog = axis.isLog;
return {
min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
dataMin: axis.dataMin,
dataMax: axis.dataMax,
userMin: axis.userMin,
userMax: axis.userMax
};
},
/**
* Get the zero plane either based on zero or on the min or max value.
* Used in bar and area plots
*/
getThreshold: function (threshold) {
var axis = this,
isLog = axis.isLog;
var realMin = isLog ? lin2log(axis.min) : axis.min,
realMax = isLog ? lin2log(axis.max) : axis.max;
if (realMin > threshold || threshold === null) {
threshold = realMin;
} else if (realMax < threshold) {
threshold = realMax;
}
return axis.translate(threshold, 0, 1, 0, 1);
},
addPlotBand: function (options) {
this.addPlotBandOrLine(options, 'plotBands');
},
addPlotLine: function (options) {
this.addPlotBandOrLine(options, 'plotLines');
},
/**
* Add a plot band or plot line after render time
*
* @param options {Object} The plotBand or plotLine configuration object
*/
addPlotBandOrLine: function (options, coll) {
var obj = new PlotLineOrBand(this, options).render(),
userOptions = this.userOptions;
if (obj) { // #2189
// Add it to the user options for exporting and Axis.update
if (coll) {
userOptions[coll] = userOptions[coll] || [];
userOptions[coll].push(options);
}
this.plotLinesAndBands.push(obj);
}
return obj;
},
/**
* Compute auto alignment for the axis label based on which side the axis is on
* and the given rotation for the label
*/
autoLabelAlign: function (rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
},
/**
* Render the tick labels to a preliminary position to get their sizes
*/
getOffset: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
tickPositions = axis.tickPositions,
ticks = axis.ticks,
horiz = axis.horiz,
side = axis.side,
invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
hasData,
showAxis,
titleOffset = 0,
titleOffsetOption,
titleMargin = 0,
axisTitleOptions = options.title,
labelOptions = options.labels,
labelOffset = 0, // reset
axisOffset = chart.axisOffset,
clipOffset = chart.clipOffset,
directionFactor = [-1, 1, 1, -1][side],
n,
i,
autoStaggerLines = 1,
maxStaggerLines = pick(labelOptions.maxStaggerLines, 5),
sortedPositions,
lastRight,
overlap,
pos,
bBox,
x,
w,
lineNo;
// For reuse in Axis.render
axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
// Set/reset staggerLines
axis.staggerLines = axis.horiz && labelOptions.staggerLines;
// Create the axisGroup and gridGroup elements on first iteration
if (!axis.axisGroup) {
axis.gridGroup = renderer.g('grid')
.attr({ zIndex: options.gridZIndex || 1 })
.add();
axis.axisGroup = renderer.g('axis')
.attr({ zIndex: options.zIndex || 2 })
.add();
axis.labelGroup = renderer.g('axis-labels')
.attr({ zIndex: labelOptions.zIndex || 7 })
.add();
}
if (hasData || axis.isLinked) {
// Set the explicit or automatic label alignment
axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation));
// Generate ticks
each(tickPositions, function (pos) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
} else {
ticks[pos].addLabel(); // update labels depending on tick interval
}
});
// Handle automatic stagger lines
if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) {
sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions;
while (autoStaggerLines < maxStaggerLines) {
lastRight = [];
overlap = false;
for (i = 0; i < sortedPositions.length; i++) {
pos = sortedPositions[i];
bBox = ticks[pos].label && ticks[pos].label.getBBox();
w = bBox ? bBox.width : 0;
lineNo = i % autoStaggerLines;
if (w) {
x = axis.translate(pos); // don't handle log
if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) {
overlap = true;
}
lastRight[lineNo] = x + w;
}
}
if (overlap) {
autoStaggerLines++;
} else {
break;
}
}
if (autoStaggerLines > 1) {
axis.staggerLines = autoStaggerLines;
}
}
each(tickPositions, function (pos) {
// left side must be align: right and right side must have align: left for labels
if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
// get the highest offset
labelOffset = mathMax(
ticks[pos].getLabelSize(),
labelOffset
);
}
});
if (axis.staggerLines) {
labelOffset *= axis.staggerLines;
axis.labelOffset = labelOffset;
}
} else { // doesn't have data
for (n in ticks) {
ticks[n].destroy();
delete ticks[n];
}
}
if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
if (!axis.axisTitle) {
axis.axisTitle = renderer.text(
axisTitleOptions.text,
0,
0,
axisTitleOptions.useHTML
)
.attr({
zIndex: 7,
rotation: axisTitleOptions.rotation || 0,
align:
axisTitleOptions.textAlign ||
{ low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
})
.css(axisTitleOptions.style)
.add(axis.axisGroup);
axis.axisTitle.isNew = true;
}
if (showAxis) {
titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10);
titleOffsetOption = axisTitleOptions.offset;
}
// hide or show the title depending on whether showEmpty is set
axis.axisTitle[showAxis ? 'show' : 'hide']();
}
// handle automatic or user set offset
axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
axis.axisTitleMargin =
pick(titleOffsetOption,
labelOffset + titleMargin +
(side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x'])
);
axisOffset[side] = mathMax(
axisOffset[side],
axis.axisTitleMargin + titleOffset + directionFactor * axis.offset
);
clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
},
/**
* Get the path for the axis line
*/
getLinePath: function (lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer.crispLine([
M,
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
L,
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
},
/**
* Position the title
*/
getTitlePosition: function () {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
fontSize = pInt(axisTitleOptions.style.fontSize || 12),
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis :
offAxis + (opposite ? this.width : 0) + offset +
(axisTitleOptions.x || 0), // x
y: horiz ?
offAxis - (opposite ? this.height : 0) + offset :
alongAxis + (axisTitleOptions.y || 0) // y
};
},
/**
* Render the axis
*/
render: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
isLog = axis.isLog,
isLinked = axis.isLinked,
tickPositions = axis.tickPositions,
axisTitle = axis.axisTitle,
stacks = axis.stacks,
ticks = axis.ticks,
minorTicks = axis.minorTicks,
alternateBands = axis.alternateBands,
stackLabelOptions = options.stackLabels,
alternateGridColor = options.alternateGridColor,
tickmarkOffset = axis.tickmarkOffset,
lineWidth = options.lineWidth,
linePath,
hasRendered = chart.hasRendered,
slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
hasData = axis.hasData,
showAxis = axis.showAxis,
from,
to;
// Mark all elements inActive before we go over and mark the active ones
each([ticks, minorTicks, alternateBands], function (coll) {
var pos;
for (pos in coll) {
coll[pos].isActive = false;
}
});
// If the series has data draw the ticks. Else only the line and title
if (hasData || isLinked) {
// minor ticks
if (axis.minorTickInterval && !axis.categories) {
each(axis.getMinorTickPositions(), function (pos) {
if (!minorTicks[pos]) {
minorTicks[pos] = new Tick(axis, pos, 'minor');
}
// render new ticks in old position
if (slideInTicks && minorTicks[pos].isNew) {
minorTicks[pos].render(null, true);
}
minorTicks[pos].render(null, false, 1);
});
}
// Major ticks. Pull out the first item and render it last so that
// we can get the position of the neighbour label. #808.
if (tickPositions.length) { // #1300
each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) {
// Reorganize the indices
i = (i === tickPositions.length - 1) ? 0 : i + 1;
// linked axes need an extra check to find out if
if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
}
// render new ticks in old position
if (slideInTicks && ticks[pos].isNew) {
ticks[pos].render(i, true);
}
ticks[pos].render(i, false, 1);
}
});
// In a categorized axis, the tick marks are displayed between labels. So
// we need to add a tick mark and grid line at the left edge of the X axis.
if (tickmarkOffset && axis.min === 0) {
if (!ticks[-1]) {
ticks[-1] = new Tick(axis, -1, null, true);
}
ticks[-1].render(-1);
}
}
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function (pos, i) {
if (i % 2 === 0 && pos < axis.max) {
if (!alternateBands[pos]) {
alternateBands[pos] = new PlotLineOrBand(axis);
}
from = pos + tickmarkOffset; // #949
to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
alternateBands[pos].options = {
from: isLog ? lin2log(from) : from,
to: isLog ? lin2log(to) : to,
color: alternateGridColor
};
alternateBands[pos].render();
alternateBands[pos].isActive = true;
}
});
}
// custom plot lines and bands
if (!axis._addedPlotLB) { // only first time
each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
axis.addPlotBandOrLine(plotLineOptions);
});
axis._addedPlotLB = true;
}
} // end if hasData
// Remove inactive ticks
each([ticks, minorTicks, alternateBands], function (coll) {
var pos,
i,
forDestruction = [],
delay = globalAnimation ? globalAnimation.duration || 500 : 0,
destroyInactiveItems = function () {
i = forDestruction.length;
while (i--) {
// When resizing rapidly, the same items may be destroyed in different timeouts,
// or the may be reactivated
if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
coll[forDestruction[i]].destroy();
delete coll[forDestruction[i]];
}
}
};
for (pos in coll) {
if (!coll[pos].isActive) {
// Render to zero opacity
coll[pos].render(pos, false, 0);
coll[pos].isActive = false;
forDestruction.push(pos);
}
}
// When the objects are finished fading out, destroy them
if (coll === alternateBands || !chart.hasRendered || !delay) {
destroyInactiveItems();
} else if (delay) {
setTimeout(destroyInactiveItems, delay);
}
});
// Static items. As the axis group is cleared on subsequent calls
// to render, these items are added outside the group.
// axis line
if (lineWidth) {
linePath = axis.getLinePath(lineWidth);
if (!axis.axisLine) {
axis.axisLine = renderer.path(linePath)
.attr({
stroke: options.lineColor,
'stroke-width': lineWidth,
zIndex: 7
})
.add(axis.axisGroup);
} else {
axis.axisLine.animate({ d: linePath });
}
// show or hide the line depending on options.showEmpty
axis.axisLine[showAxis ? 'show' : 'hide']();
}
if (axisTitle && showAxis) {
axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
axis.getTitlePosition()
);
axisTitle.isNew = false;
}
// Stacked totals:
if (stackLabelOptions && stackLabelOptions.enabled) {
var stackKey, oneStack, stackCategory,
stackTotalGroup = axis.stackTotalGroup;
// Create a separate group for the stack total labels
if (!stackTotalGroup) {
axis.stackTotalGroup = stackTotalGroup =
renderer.g('stack-labels')
.attr({
visibility: VISIBLE,
zIndex: 6
})
.add();
}
// plotLeft/Top will change when y axis gets wider so we need to translate the
// stackTotalGroup at every render call. See bug #506 and #516
stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
// Render each stack total
for (stackKey in stacks) {
oneStack = stacks[stackKey];
for (stackCategory in oneStack) {
oneStack[stackCategory].render(stackTotalGroup);
}
}
}
// End stacked totals
axis.isDirty = false;
},
/**
* Remove a plot band or plot line from the chart by id
* @param {Object} id
*/
removePlotBandOrLine: function (id) {
var plotLinesAndBands = this.plotLinesAndBands,
options = this.options,
userOptions = this.userOptions,
i = plotLinesAndBands.length;
while (i--) {
if (plotLinesAndBands[i].id === id) {
plotLinesAndBands[i].destroy();
}
}
each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
i = arr.length;
while (i--) {
if (arr[i].id === id) {
erase(arr, arr[i]);
}
}
});
},
/**
* Update the axis title by options
*/
setTitle: function (newTitleOptions, redraw) {
this.update({ title: newTitleOptions }, redraw);
},
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
redraw: function () {
var axis = this,
chart = axis.chart,
pointer = chart.pointer;
// hide tooltip and hover states
if (pointer.reset) {
pointer.reset(true);
}
// render the axis
axis.render();
// move plot lines and bands
each(axis.plotLinesAndBands, function (plotLine) {
plotLine.render();
});
// mark associated series as dirty and ready for redraw
each(axis.series, function (series) {
series.isDirty = true;
});
},
/**
* Build the stacks from top down
*/
buildStacks: function () {
var series = this.series,
i = series.length;
if (!this.isXAxis) {
while (i--) {
series[i].setStackedPoints();
}
// Loop up again to compute percent stack
if (this.usePercentage) {
for (i = 0; i < series.length; i++) {
series[i].setPercentStacks();
}
}
}
},
/**
* Set new axis categories and optionally redraw
* @param {Array} categories
* @param {Boolean} redraw
*/
setCategories: function (categories, redraw) {
this.update({ categories: categories }, redraw);
},
/**
* Destroys an Axis instance.
*/
destroy: function (keepEvents) {
var axis = this,
stacks = axis.stacks,
stackKey,
plotLinesAndBands = axis.plotLinesAndBands,
i;
// Remove the events
if (!keepEvents) {
removeEvent(axis);
}
// Destroy each stack total
for (stackKey in stacks) {
destroyObjectProperties(stacks[stackKey]);
stacks[stackKey] = null;
}
// Destroy collections
each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
destroyObjectProperties(coll);
});
i = plotLinesAndBands.length;
while (i--) { // #1975
plotLinesAndBands[i].destroy();
}
// Destroy local variables
each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) {
if (axis[prop]) {
axis[prop] = axis[prop].destroy();
}
});
}
}; // end Axis
/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
function Tooltip() {
this.init.apply(this, arguments);
}
Tooltip.prototype = {
init: function (chart, options) {
var borderWidth = options.borderWidth,
style = options.style,
padding = pInt(style.padding);
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = UNDEFINED;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = { x: 0, y: 0 };
// The tooltip is initially hidden
this.isHidden = true;
// create the label
this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip')
.attr({
padding: padding,
fill: options.backgroundColor,
'stroke-width': borderWidth,
r: options.borderRadius,
zIndex: 8
})
.css(style)
.css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
.add()
.attr({ y: -999 }); // #2301
// When using canVG the shadow shows up as a gray circle
// even if the tooltip is hidden.
if (!useCanVG) {
this.label.shadow(options.shadow);
}
// Public property for getting the shared state.
this.shared = options.shared;
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function () {
each(this.crosshairs, function (crosshair) {
if (crosshair) {
crosshair.destroy();
}
});
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function (x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden;
// get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// move to the intermediate value
tooltip.label.attr(now);
// run on next tick of the mouse tracker
if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) {
// never allow two timeouts
clearTimeout(this.tooltipTimeout);
// set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function () {
// The interval function may still be running during destroy, so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function () {
var tooltip = this,
hoverPoints;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
if (!this.isHidden) {
hoverPoints = this.chart.hoverPoints;
this.hideTimer = setTimeout(function () {
tooltip.label.fadeOut();
tooltip.isHidden = true;
}, pick(this.options.hideDelay, 500));
// hide previous hoverPoints and set new
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
this.chart.hoverPoints = null;
}
},
/**
* Hide the crosshairs
*/
hideCrosshairs: function () {
each(this.crosshairs, function (crosshair) {
if (crosshair) {
crosshair.hide();
}
});
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function (points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotX = 0,
plotY = 0,
yAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === UNDEFINED) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function (point) {
yAxis = point.series.yAxis;
plotX += point.plotX;
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, mathRound);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function (boxWidth, boxHeight, point) {
// Set up the variables
var chart = this.chart,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
distance = pick(this.options.distance, 12),
pointX = point.plotX,
pointY = point.plotY,
x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance),
y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip
alignedRight;
// It is too far to the left, adjust it
if (x < 7) {
x = plotLeft + mathMax(pointX, 0) + distance;
}
// Test to see if the tooltip is too far to the right,
// if it is, move it back to be inside and then up to not cover the point.
if ((x + boxWidth) > (plotLeft + plotWidth)) {
x -= (x + boxWidth) - (plotLeft + plotWidth);
y = pointY - boxHeight + plotTop - distance;
alignedRight = true;
}
// If it is now above the plot area, align it to the top of the plot area
if (y < plotTop + 5) {
y = plotTop + 5;
// If the tooltip is still covering the point, move it below instead
if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) {
y = pointY + plotTop + distance; // below
}
}
// Now if the tooltip is below the chart, move it up. It's better to cover the
// point than to disappear outside the chart. #834.
if (y + boxHeight > plotTop + plotHeight) {
y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below
}
return {x: x, y: y};
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*/
defaultFormatter: function (tooltip) {
var items = this.points || splat(this),
series = items[0].series,
s;
// build the header
s = [series.tooltipHeaderFormatter(items[0])];
// build the values
each(items, function (item) {
series = item.series;
s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
});
// footer
s.push(tooltip.options.footerFormat || '');
return s.join('');
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function (point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.label,
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
borderColor,
crosshairsOptions = options.crosshairs,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(point, function (item) {
item.setState(HOVER_STATE);
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr('opacity', 1).show();
}
// update text
label.attr({
text: text
});
// set the stroke color of the box
borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
label.attr({
stroke: borderColor
});
tooltip.updatePosition({ plotX: x, plotY: y });
this.isHidden = false;
}
// crosshairs
if (crosshairsOptions) {
crosshairsOptions = splat(crosshairsOptions); // [x, y]
var path,
i = crosshairsOptions.length,
attribs,
axis,
val,
series;
while (i--) {
series = point.series;
axis = series[i ? 'yAxis' : 'xAxis'];
if (crosshairsOptions[i] && axis) {
val = i ? pick(point.stackY, point.y) : point.x; // #814
if (axis.isLog) { // #1671
val = log2lin(val);
}
if (i === 1 && series.modifyValue) { // #1205, #2316
val = series.modifyValue(val);
}
path = axis.getPlotLinePath(
val,
1
);
if (tooltip.crosshairs[i]) {
tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE });
} else {
attribs = {
'stroke-width': crosshairsOptions[i].width || 1,
stroke: crosshairsOptions[i].color || '#C0C0C0',
zIndex: crosshairsOptions[i].zIndex || 2
};
if (crosshairsOptions[i].dashStyle) {
attribs.dashstyle = crosshairsOptions[i].dashStyle;
}
tooltip.crosshairs[i] = chart.renderer.path(path)
.attr(attribs)
.add();
}
}
}
}
fireEvent(chart, 'tooltipRefresh', {
text: text,
x: x + chart.plotLeft,
y: y + chart.plotTop,
borderColor: borderColor
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function (point) {
var chart = this.chart,
label = this.label,
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
mathRound(pos.x),
mathRound(pos.y),
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
}
};
/**
* The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
* Subsequent methods should be named differently from what they are doing.
* @param {Object} chart The Chart instance
* @param {Object} options The root options object
*/
function Pointer(chart, options) {
this.init(chart, options);
}
Pointer.prototype = {
/**
* Initialize Pointer
*/
init: function (chart, options) {
var chartOptions = options.chart,
chartEvents = chartOptions.events,
zoomType = useCanVG ? '' : chartOptions.zoomType,
inverted = chart.inverted,
zoomX,
zoomY;
// Store references
this.options = options;
this.chart = chart;
// Zoom status
this.zoomX = zoomX = /x/.test(zoomType);
this.zoomY = zoomY = /y/.test(zoomType);
this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
// Do we need to handle click on a touch device?
this.runChartClick = chartEvents && !!chartEvents.click;
this.pinchDown = [];
this.lastValidTouch = {};
if (options.tooltip.enabled) {
chart.tooltip = new Tooltip(chart, options.tooltip);
}
this.setDOMEvents();
},
/**
* Add crossbrowser support for chartX and chartY
* @param {Object} e The event object in standard browsers
*/
normalize: function (e, chartPosition) {
var chartX,
chartY,
ePos;
// common IE normalizing
e = e || win.event;
if (!e.target) {
e.target = e.srcElement;
}
// Framework specific normalizing (#1165)
e = washMouseEvent(e);
// iOS
ePos = e.touches ? e.touches.item(0) : e;
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = offset(this.chart.container);
}
// chartX and chartY
if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
// for IE10 quirks mode within framesets
chartY = e.y;
} else {
chartX = ePos.pageX - chartPosition.left;
chartY = ePos.pageY - chartPosition.top;
}
return extend(e, {
chartX: mathRound(chartX),
chartY: mathRound(chartY)
});
},
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A pointer event
*/
getCoordinates: function (e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each(this.chart.axes, function (axis) {
coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
});
});
return coordinates;
},
/**
* Return the index in the tooltipPoints array, corresponding to pixel position in
* the plot area.
*/
getIndex: function (e) {
var chart = this.chart;
return chart.inverted ?
chart.plotHeight + chart.plotTop - e.chartY :
e.chartX - chart.plotLeft;
},
/**
* With line type charts with a single tracker, get the point closest to the mouse.
* Run Point.onMouseOver and display tooltip for the point or points.
*/
runPointActions: function (e) {
var pointer = this,
chart = pointer.chart,
series = chart.series,
tooltip = chart.tooltip,
point,
points,
hoverPoint = chart.hoverPoint,
hoverSeries = chart.hoverSeries,
i,
j,
distance = chart.chartWidth,
index = pointer.getIndex(e),
anchor;
// shared tooltip
if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) {
points = [];
// loop over all series and find the ones with points closest to the mouse
i = series.length;
for (j = 0; j < i; j++) {
if (series[j].visible &&
series[j].options.enableMouseTracking !== false &&
!series[j].noSharedTooltip && series[j].tooltipPoints.length) {
point = series[j].tooltipPoints[index];
if (point && point.series) { // not a dummy point, #1544
point._dist = mathAbs(index - point.clientX);
distance = mathMin(distance, point._dist);
points.push(point);
}
}
}
// remove furthest points
i = points.length;
while (i--) {
if (points[i]._dist > distance) {
points.splice(i, 1);
}
}
// refresh the tooltip if necessary
if (points.length && (points[0].clientX !== pointer.hoverX)) {
tooltip.refresh(points, e);
pointer.hoverX = points[0].clientX;
}
}
// separate tooltip and general mouse events
if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker
// get the point
point = hoverSeries.tooltipPoints[index];
// a new point is hovered, refresh the tooltip
if (point && point !== hoverPoint) {
// trigger the events
point.onMouseOver(e);
}
} else if (tooltip && tooltip.followPointer && !tooltip.isHidden) {
anchor = tooltip.getAnchor([{}], e);
tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
}
},
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*
* @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
*/
reset: function (allowMove) {
var pointer = this,
chart = pointer.chart,
hoverSeries = chart.hoverSeries,
hoverPoint = chart.hoverPoint,
tooltip = chart.tooltip,
tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
// Narrow in allowMove
allowMove = allowMove && tooltip && tooltipPoints;
// Check if the points have moved outside the plot area, #1003
if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
allowMove = false;
}
// Just move the tooltip, #349
if (allowMove) {
tooltip.refresh(tooltipPoints);
// Full reset
} else {
if (hoverPoint) {
hoverPoint.onMouseOut();
}
if (hoverSeries) {
hoverSeries.onMouseOut();
}
if (tooltip) {
tooltip.hide();
tooltip.hideCrosshairs();
}
pointer.hoverX = null;
}
},
/**
* Scale series groups to a certain scale and translation
*/
scaleGroups: function (attribs, clip) {
var chart = this.chart,
seriesAttribs;
// Scale each series
each(chart.series, function (series) {
seriesAttribs = attribs || series.getPlotBox(); // #1701
if (series.xAxis && series.xAxis.zoomEnabled) {
series.group.attr(seriesAttribs);
if (series.markerGroup) {
series.markerGroup.attr(seriesAttribs);
series.markerGroup.clip(clip ? chart.clipRect : null);
}
if (series.dataLabelsGroup) {
series.dataLabelsGroup.attr(seriesAttribs);
}
}
});
// Clip
chart.clipRect.attr(clip || chart.clipBox);
},
/**
* Run translation operations
*/
pinchTranslate: function (zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (zoomHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (zoomVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
},
/**
* Run translation operations for each direction (horizontal and vertical) independently
*/
pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
var chart = this.chart,
xy = horiz ? 'x' : 'y',
XY = horiz ? 'X' : 'Y',
sChartXY = 'chart' + XY,
wh = horiz ? 'width' : 'height',
plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
selectionWH,
selectionXY,
clipXY,
scale = forcedScale || 1,
inverted = chart.inverted,
bounds = chart.bounds[horiz ? 'h' : 'v'],
singleTouch = pinchDown.length === 1,
touch0Start = pinchDown[0][sChartXY],
touch0Now = touches[0][sChartXY],
touch1Start = !singleTouch && pinchDown[1][sChartXY],
touch1Now = !singleTouch && touches[1][sChartXY],
outOfBounds,
transformScale,
scaleKey,
setScale = function () {
if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
}
clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
};
// Set the scale, first pass
setScale();
selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
// Out of bounds
if (selectionXY < bounds.min) {
selectionXY = bounds.min;
outOfBounds = true;
} else if (selectionXY + selectionWH > bounds.max) {
selectionXY = bounds.max - selectionWH;
outOfBounds = true;
}
// Is the chart dragged off its bounds, determined by dataMin and dataMax?
if (outOfBounds) {
// Modify the touchNow position in order to create an elastic drag movement. This indicates
// to the user that the chart is responsive but can't be dragged further.
touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
if (!singleTouch) {
touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
}
// Set the scale, second pass to adapt to the modified touchNow positions
setScale();
} else {
lastValidTouch[xy] = [touch0Now, touch1Now];
}
// Set geometry for clipping, selection and transformation
if (!inverted) { // TODO: implement clipping for inverted charts
clip[xy] = clipXY - plotLeftTop;
clip[wh] = selectionWH;
}
scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
transformScale = inverted ? 1 / scale : scale;
selectionMarker[wh] = selectionWH;
selectionMarker[xy] = selectionXY;
transform[scaleKey] = scale;
transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
},
/**
* Handle touch events with two touches
*/
pinch: function (e) {
var self = this,
chart = self.chart,
pinchDown = self.pinchDown,
followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove,
touches = e.touches,
touchesLength = touches.length,
lastValidTouch = self.lastValidTouch,
zoomHor = self.zoomHor || self.pinchHor,
zoomVert = self.zoomVert || self.pinchVert,
hasZoom = zoomHor || zoomVert,
selectionMarker = self.selectionMarker,
transform = {},
fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
chart.runTrackerClick) || chart.runChartClick),
clip = {};
// On touch devices, only proceed to trigger click if a handler is defined
if ((hasZoom || followTouchMove) && !fireClickEvent) {
e.preventDefault();
}
// Normalize each touch
map(touches, function (e) {
return self.normalize(e);
});
// Register the touch start position
if (e.type === 'touchstart') {
each(touches, function (e, i) {
pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
});
lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
// Identify the data bounds in pixels
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
minPixelPadding = axis.minPixelPadding,
min = axis.toPixels(axis.dataMin),
max = axis.toPixels(axis.dataMax),
absMin = mathMin(min, max),
absMax = mathMax(min, max);
// Store the bounds for use in the touchmove handler
bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
}
});
// Event type is touchmove, handle panning and pinching
} else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
// Set the marker
if (!selectionMarker) {
self.selectionMarker = selectionMarker = extend({
destroy: noop
}, chart.plotBox);
}
self.pinchTranslate(zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
self.hasPinched = hasZoom;
// Scale and translate the groups to provide visual feedback during pinching
self.scaleGroups(transform, clip);
// Optionally move the tooltip on touchmove
if (!hasZoom && followTouchMove && touchesLength === 1) {
this.runPointActions(self.normalize(e));
}
}
},
/**
* Start a drag operation
*/
dragStart: function (e) {
var chart = this.chart;
// Record the start position
chart.mouseIsDown = e.type;
chart.cancelClick = false;
chart.mouseDownX = this.mouseDownX = e.chartX;
chart.mouseDownY = this.mouseDownY = e.chartY;
},
/**
* Perform a drag operation in response to a mousemove event while the mouse is down
*/
drag: function (e) {
var chart = this.chart,
chartOptions = chart.options.chart,
chartX = e.chartX,
chartY = e.chartY,
zoomHor = this.zoomHor,
zoomVert = this.zoomVert,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
clickedInside,
size,
mouseDownX = this.mouseDownX,
mouseDownY = this.mouseDownY;
// If the mouse is outside the plot area, adjust to cooordinates
// inside to prevent the selection marker from going outside
if (chartX < plotLeft) {
chartX = plotLeft;
} else if (chartX > plotLeft + plotWidth) {
chartX = plotLeft + plotWidth;
}
if (chartY < plotTop) {
chartY = plotTop;
} else if (chartY > plotTop + plotHeight) {
chartY = plotTop + plotHeight;
}
// determine if the mouse has moved more than 10px
this.hasDragged = Math.sqrt(
Math.pow(mouseDownX - chartX, 2) +
Math.pow(mouseDownY - chartY, 2)
);
if (this.hasDragged > 10) {
clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
// make a selection
if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) {
if (!this.selectionMarker) {
this.selectionMarker = chart.renderer.rect(
plotLeft,
plotTop,
zoomHor ? 1 : plotWidth,
zoomVert ? 1 : plotHeight,
0
)
.attr({
fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
zIndex: 7
})
.add();
}
}
// adjust the width of the selection marker
if (this.selectionMarker && zoomHor) {
size = chartX - mouseDownX;
this.selectionMarker.attr({
width: mathAbs(size),
x: (size > 0 ? 0 : size) + mouseDownX
});
}
// adjust the height of the selection marker
if (this.selectionMarker && zoomVert) {
size = chartY - mouseDownY;
this.selectionMarker.attr({
height: mathAbs(size),
y: (size > 0 ? 0 : size) + mouseDownY
});
}
// panning
if (clickedInside && !this.selectionMarker && chartOptions.panning) {
chart.pan(e, chartOptions.panning);
}
}
},
/**
* On mouse up or touch end across the entire document, drop the selection.
*/
drop: function (e) {
var chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: [],
originalEvent: e.originalEvent || e
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.x,
selectionTop = selectionBox.y,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var horiz = axis.horiz,
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height));
if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
selectionData[axis.xOrY + 'Axis'].push({
axis: axis,
min: mathMin(selectionMin, selectionMax), // for reversed axes,
max: mathMax(selectionMin, selectionMax)
});
runZoom = true;
}
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function (args) {
chart.zoom(extend(args, hasPinched ? { animation: false } : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, { cursor: chart._cursor });
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
},
onContainerMouseDown: function (e) {
e = this.normalize(e);
// issue #295, dragging not always working in Firefox
if (e.preventDefault) {
e.preventDefault();
}
this.dragStart(e);
},
onDocumentMouseUp: function (e) {
this.drop(e);
},
/**
* Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
* Issue #149 workaround. The mouseleave event does not always fire.
*/
onDocumentMouseMove: function (e) {
var chart = this.chart,
chartPosition = this.chartPosition,
hoverSeries = chart.hoverSeries;
e = this.normalize(e, chartPosition);
// If we're outside, hide the tooltip
if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') &&
!chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
this.reset();
}
},
/**
* When mouse leaves the container, hide the tooltip.
*/
onContainerMouseLeave: function () {
this.reset();
this.chartPosition = null; // also reset the chart position, used in #149 fix
},
// The mousemove, touchmove and touchstart event handler
onContainerMouseMove: function (e) {
var chart = this.chart;
// normalize
e = this.normalize(e);
// #295
e.returnValue = false;
if (chart.mouseIsDown === 'mousedown') {
this.drag(e);
}
// Show the tooltip and run mouse over events (#977)
if ((this.inClass(e.target, 'highcharts-tracker') ||
chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
this.runPointActions(e);
}
},
/**
* Utility to detect whether an element has, or has a parent with, a specific
* class name. Used on detection of tracker objects and on deciding whether
* hovering the tooltip should cause the active series to mouse out.
*/
inClass: function (element, className) {
var elemClassName;
while (element) {
elemClassName = attr(element, 'class');
if (elemClassName) {
if (elemClassName.indexOf(className) !== -1) {
return true;
} else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
return false;
}
}
element = element.parentNode;
}
},
onTrackerMouseOut: function (e) {
var series = this.chart.hoverSeries;
if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) {
series.onMouseOut();
}
},
onContainerClick: function (e) {
var chart = this.chart,
hoverPoint = chart.hoverPoint,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
inverted = chart.inverted,
chartPosition,
plotX,
plotY;
e = this.normalize(e);
e.cancelBubble = true; // IE specific
if (!chart.cancelClick) {
// On tracker click, fire the series and point events. #783, #1583
if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
chartPosition = this.chartPosition;
plotX = hoverPoint.plotX;
plotY = hoverPoint.plotY;
// add page position info
extend(hoverPoint, {
pageX: chartPosition.left + plotLeft +
(inverted ? chart.plotWidth - plotY : plotX),
pageY: chartPosition.top + plotTop +
(inverted ? chart.plotHeight - plotX : plotY)
});
// the series click event
fireEvent(hoverPoint.series, 'click', extend(e, {
point: hoverPoint
}));
// the point click event
if (chart.hoverPoint) { // it may be destroyed (#1844)
hoverPoint.firePointEvent('click', e);
}
// When clicking outside a tracker, fire a chart event
} else {
extend(e, this.getCoordinates(e));
// fire a click event in the chart
if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
fireEvent(chart, 'click', e);
}
}
}
},
onContainerTouchStart: function (e) {
var chart = this.chart;
if (e.touches.length === 1) {
e = this.normalize(e);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
// Prevent the click pseudo event from firing unless it is set in the options
/*if (!chart.runChartClick) {
e.preventDefault();
}*/
// Run mouse events and display tooltip etc
this.runPointActions(e);
this.pinch(e);
} else {
// Hide the tooltip on touching outside the plot area (#1203)
this.reset();
}
} else if (e.touches.length === 2) {
this.pinch(e);
}
},
onContainerTouchMove: function (e) {
if (e.touches.length === 1 || e.touches.length === 2) {
this.pinch(e);
}
},
onDocumentTouchEnd: function (e) {
this.drop(e);
},
/**
* Set the JS DOM events on the container and document. This method should contain
* a one-to-one assignment between methods and their handlers. Any advanced logic should
* be moved to the handler reflecting the event's name.
*/
setDOMEvents: function () {
var pointer = this,
container = pointer.chart.container,
events;
this._events = events = [
[container, 'onmousedown', 'onContainerMouseDown'],
[container, 'onmousemove', 'onContainerMouseMove'],
[container, 'onclick', 'onContainerClick'],
[container, 'mouseleave', 'onContainerMouseLeave'],
[doc, 'mousemove', 'onDocumentMouseMove'],
[doc, 'mouseup', 'onDocumentMouseUp']
];
if (hasTouch) {
events.push(
[container, 'ontouchstart', 'onContainerTouchStart'],
[container, 'ontouchmove', 'onContainerTouchMove'],
[doc, 'touchend', 'onDocumentTouchEnd']
);
}
each(events, function (eventConfig) {
// First, create the callback function that in turn calls the method on Pointer
pointer['_' + eventConfig[2]] = function (e) {
pointer[eventConfig[2]](e);
};
// Now attach the function, either as a direct property or through addEvent
if (eventConfig[1].indexOf('on') === 0) {
eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]];
} else {
addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
}
});
},
/**
* Destroys the Pointer object and disconnects DOM events.
*/
destroy: function () {
var pointer = this;
// Release all DOM events
each(pointer._events, function (eventConfig) {
if (eventConfig[1].indexOf('on') === 0) {
eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE
} else {
removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
}
});
delete pointer._events;
// memory and CPU leak
clearInterval(pointer.tooltipTimeout);
}
};
/**
* The overview of the chart's series
*/
function Legend(chart, options) {
this.init(chart, options);
}
Legend.prototype = {
/**
* Initialize the legend
*/
init: function (chart, options) {
var legend = this,
itemStyle = options.itemStyle,
padding = pick(options.padding, 8),
itemMarginTop = options.itemMarginTop || 0;
this.options = options;
if (!options.enabled) {
return;
}
legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype
legend.itemStyle = itemStyle;
legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
legend.itemMarginTop = itemMarginTop;
legend.padding = padding;
legend.initialItemX = padding;
legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
legend.maxItemWidth = 0;
legend.chart = chart;
legend.itemHeight = 0;
legend.lastLineHeight = 0;
// Render it
legend.render();
// move checkboxes
addEvent(legend.chart, 'endResize', function () {
legend.positionCheckboxes();
});
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function (item, visible) {
var legend = this,
options = legend.options,
legendItem = item.legendItem,
legendLine = item.legendLine,
legendSymbol = item.legendSymbol,
hiddenColor = legend.itemHiddenStyle.color,
textColor = visible ? options.itemStyle.color : hiddenColor,
symbolColor = visible ? item.color : hiddenColor,
markerOptions = item.options && item.options.marker,
symbolAttr = {
stroke: symbolColor,
fill: symbolColor
},
key,
val;
if (legendItem) {
legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
}
if (legendLine) {
legendLine.attr({ stroke: symbolColor });
}
if (legendSymbol) {
// Apply marker options
if (markerOptions && legendSymbol.isMarker) { // #585
markerOptions = item.convertAttribs(markerOptions);
for (key in markerOptions) {
val = markerOptions[key];
if (val !== UNDEFINED) {
symbolAttr[key] = val;
}
}
}
legendSymbol.attr(symbolAttr);
}
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function (item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox;
if (item.legendGroup) {
item.legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function (item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function () {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
css(checkbox, {
left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX,
top: top + PX,
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function () {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({ zIndex: 1 })
.css(titleOptions.style)
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({ translateY: titleHeight });
}
this.titleHeight = titleHeight;
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function (item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = options.symbolWidth,
symbolPadding = options.symbolPadding,
itemStyle = legend.itemStyle,
itemHiddenStyle = legend.itemHiddenStyle,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 8) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
series = item.series || item,
itemOptions = series.options,
showCheckbox = itemOptions.showCheckbox,
useHTML = options.useHTML;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.attr({ zIndex: 1 })
.add(legend.scrollGroup);
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline,
useHTML
)
.css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Set the events on the item group, or in case of useHTML, the item itself (#1249)
(useHTML ? li : item.legendGroup).on('mouseover', function () {
item.setState(HOVER_STATE);
li.css(legend.options.itemHoverStyle);
})
.on('mouseout', function () {
li.css(item.visible ? itemStyle : itemHiddenStyle);
item.setState();
})
.on('click', function (event) {
var strLegendItemClick = 'legendItemClick',
fnLegendItemClick = function () {
item.setVisible();
};
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
} else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
// Colorize the items
legend.colorizeItem(item, item.visible);
// add the HTML checkbox on top
if (itemOptions && showCheckbox) {
item.checkbox = createElement('input', {
type: 'checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, options.itemCheckboxStyle, chart.container);
addEvent(item.checkbox, 'click', function (event) {
var target = event.target;
fireEvent(item, 'checkboxClick', {
checked: target.checked
},
function () {
item.select();
}
);
});
}
}
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.legendItemWidth =
options.itemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance +
(showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = bBox.height;
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
legend.lastLineHeight = 0; // reset for next line
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || mathMax(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function () {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding,
legendBorderWidth = options.borderWidth,
legendBackgroundColor = options.backgroundColor;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({ zIndex: 7 })
.add();
legend.contentGroup = renderer.g()
.attr({ zIndex: 1 }) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = [];
each(chart.series, function (serie) {
var seriesOptions = serie.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, seriesOptions.linkedTo === UNDEFINED ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
allItems = allItems.concat(
serie.legendItems ||
(seriesOptions.legendType === 'point' ?
serie.data :
serie)
);
});
// sort by legendIndex
stableSort(allItems, function (a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
each(allItems, function (item) {
legend.renderItem(item);
});
// Draw the border
legendWidth = options.width || legend.offsetWidth;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
if (legendBorderWidth || legendBackgroundColor) {
legendWidth += padding;
legendHeight += padding;
if (!box) {
legend.box = box = renderer.rect(
0,
0,
legendWidth,
legendHeight,
options.borderRadius,
legendBorderWidth || 0
).attr({
stroke: options.borderColor,
'stroke-width': legendBorderWidth || 0,
fill: legendBackgroundColor || NONE
})
.add(legendGroup)
.shadow(options.shadow);
box.isNew = true;
} else if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp(null, null, null, legendWidth, legendHeight)
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function (item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function (legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
pageCount,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav;
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = mathMin(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
if (legendHeight > spaceHeight && !options.useHTML) {
this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight;
this.pageCount = pageCount = mathCeil(legendHeight / clipHeight);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, 0, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipRect.attr({
height: clipHeight
});
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.css(navOptions.style)
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipRect.attr({
height: chart.chartHeight
});
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function (scrollBy, animation) {
var pageCount = this.pageCount,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + this.pageCount
});
this.down.attr({
x: 18 + this.pager.getBBox().width, // adjust to text width
fill: currentPage === pageCount ? inactiveColor : activeColor
})
.css({
cursor: currentPage === pageCount ? 'default' : 'pointer'
});
scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1;
this.scrollGroup.animate({
translateY: scrollOffset
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview.
// TODO: When IE11 is released, check again for this bug, and remove the fix
// or make a better one.
if (/Trident\/7\.0/.test(userAgent)) {
wrap(Legend.prototype, 'positionItem', function (proceed, item) {
var legend = this,
runPositionItem = function () {
proceed.call(legend, item);
};
if (legend.chart.renderer.forExport) {
runPositionItem();
} else {
setTimeout(runPositionItem);
}
});
}
/**
* The chart class
* @param {Object} options
* @param {Function} callback Function to run when the chart has loaded
*/
function Chart() {
this.init.apply(this, arguments);
}
Chart.prototype = {
/**
* Initialize the chart
*/
init: function (userOptions, callback) {
// Handle regular options
var options,
seriesOptions = userOptions.series; // skip merging data points to increase performance
userOptions.series = null;
options = merge(defaultOptions, userOptions); // do the merge
options.series = userOptions.series = seriesOptions; // set back the series data
var optionsChart = options.chart;
// Create margin & spacing array
this.margin = this.splashArray('margin', optionsChart);
this.spacing = this.splashArray('spacing', optionsChart);
var chartEvents = optionsChart.events;
//this.runChartClick = chartEvents && !!chartEvents.click;
this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
this.callback = callback;
this.isResizing = 0;
this.options = options;
//chartTitleOptions = UNDEFINED;
//chartSubtitleOptions = UNDEFINED;
this.axes = [];
this.series = [];
this.hasCartesianSeries = optionsChart.showAxes;
//this.axisOffset = UNDEFINED;
//this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
//this.inverted = UNDEFINED;
//this.loadingShown = UNDEFINED;
//this.container = UNDEFINED;
//this.chartWidth = UNDEFINED;
//this.chartHeight = UNDEFINED;
//this.marginRight = UNDEFINED;
//this.marginBottom = UNDEFINED;
//this.containerWidth = UNDEFINED;
//this.containerHeight = UNDEFINED;
//this.oldChartWidth = UNDEFINED;
//this.oldChartHeight = UNDEFINED;
//this.renderTo = UNDEFINED;
//this.renderToClone = UNDEFINED;
//this.spacingBox = UNDEFINED
//this.legend = UNDEFINED;
// Elements
//this.chartBackground = UNDEFINED;
//this.plotBackground = UNDEFINED;
//this.plotBGImage = UNDEFINED;
//this.plotBorder = UNDEFINED;
//this.loadingDiv = UNDEFINED;
//this.loadingSpan = UNDEFINED;
var chart = this,
eventType;
// Add the chart to the global lookup
chart.index = charts.length;
charts.push(chart);
// Set up auto resize
if (optionsChart.reflow !== false) {
addEvent(chart, 'load', function () {
chart.initReflow();
});
}
// Chart event handlers
if (chartEvents) {
for (eventType in chartEvents) {
addEvent(chart, eventType, chartEvents[eventType]);
}
}
chart.xAxis = [];
chart.yAxis = [];
// Expose methods and variables
chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
chart.pointCount = 0;
chart.counters = new ChartCounters();
chart.firstRender();
},
/**
* Initialize an individual series, called internally before render time
*/
initSeries: function (options) {
var chart = this,
optionsChart = chart.options.chart,
type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
series,
constr = seriesTypes[type];
// No such series type
if (!constr) {
error(17, true);
}
series = new constr();
series.init(this, options);
return series;
},
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
* @return {Object} series The newly created series object
*/
addSeries: function (options, redraw, animation) {
var series,
chart = this;
if (options) {
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', { options: options }, function () {
series = chart.initSeries(options);
chart.isDirtyLegend = true; // the series array is out of sync with the display
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
return series;
},
/**
* Add an axis to the chart
* @param {Object} options The axis option
* @param {Boolean} isX Whether it is an X axis or a value axis
*/
addAxis: function (options, isX, redraw, animation) {
var key = isX ? 'xAxis' : 'yAxis',
chartOptions = this.options,
axis;
/*jslint unused: false*/
axis = new Axis(this, merge(options, {
index: this[key].length,
isX: isX
}));
/*jslint unused: true*/
// Push the new axis options to the chart options
chartOptions[key] = splat(chartOptions[key] || {});
chartOptions[key].push(options);
if (pick(redraw, true)) {
this.redraw(animation);
}
},
/**
* Check whether a given point is within the plot area
*
* @param {Number} plotX Pixel x relative to the plot area
* @param {Number} plotY Pixel y relative to the plot area
* @param {Boolean} inverted Whether the chart is inverted
*/
isInsidePlot: function (plotX, plotY, inverted) {
var x = inverted ? plotY : plotX,
y = inverted ? plotX : plotY;
return x >= 0 &&
x <= this.plotWidth &&
y >= 0 &&
y <= this.plotHeight;
},
/**
* Adjust all axes tick amounts
*/
adjustTickAmounts: function () {
if (this.options.chart.alignTicks !== false) {
each(this.axes, function (axis) {
axis.adjustTickAmount();
});
}
this.maxTicks = null;
},
/**
* Redraw legend, axes or series based on updated data
*
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
redraw: function (animation) {
var chart = this,
axes = chart.axes,
series = chart.series,
pointer = chart.pointer,
legend = chart.legend,
redrawLegend = chart.isDirtyLegend,
hasStackedSeries,
hasDirtyStacks,
isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
seriesLength = series.length,
i = seriesLength,
serie,
renderer = chart.renderer,
isHiddenChart = renderer.isHidden(),
afterRedraw = [];
setAnimation(animation, chart);
if (isHiddenChart) {
chart.cloneRenderTo();
}
// Adjust title layout (reflow multiline text)
chart.layOutTitles();
// link stacked series
while (i--) {
serie = series[i];
if (serie.options.stacking) {
hasStackedSeries = true;
if (serie.isDirty) {
hasDirtyStacks = true;
break;
}
}
}
if (hasDirtyStacks) { // mark others as dirty
i = seriesLength;
while (i--) {
serie = series[i];
if (serie.options.stacking) {
serie.isDirty = true;
}
}
}
// handle updated data in the series
each(series, function (serie) {
if (serie.isDirty) { // prepare the data so axis can read it
if (serie.options.legendType === 'point') {
redrawLegend = true;
}
}
});
// handle added or removed series
if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
// draw legend graphics
legend.render();
chart.isDirtyLegend = false;
}
// reset stacks
if (hasStackedSeries) {
chart.getStacks();
}
if (chart.hasCartesianSeries) {
if (!chart.isResizing) {
// reset maxTicks
chart.maxTicks = null;
// set axes scales
each(axes, function (axis) {
axis.setScale();
});
}
chart.adjustTickAmounts();
chart.getMargins();
// If one axis is dirty, all axes must be redrawn (#792, #2169)
each(axes, function (axis) {
if (axis.isDirty) {
isDirtyBox = true;
}
});
// redraw axes
each(axes, function (axis) {
// Fire 'afterSetExtremes' only if extremes are set
if (axis.isDirtyExtremes) { // #821
axis.isDirtyExtremes = false;
afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
delete axis.eventArgs;
});
}
if (isDirtyBox || hasStackedSeries) {
axis.redraw();
}
});
}
// the plot areas size has changed
if (isDirtyBox) {
chart.drawChartBox();
}
// redraw affected series
each(series, function (serie) {
if (serie.isDirty && serie.visible &&
(!serie.isCartesian || serie.xAxis)) { // issue #153
serie.redraw();
}
});
// move tooltip or reset
if (pointer && pointer.reset) {
pointer.reset(true);
}
// redraw if canvas
renderer.draw();
// fire the event
fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
if (isHiddenChart) {
chart.cloneRenderTo(true);
}
// Fire callbacks that are put on hold until after the redraw
each(afterRedraw, function (callback) {
callback.call();
});
},
/**
* Dim the chart and show a loading text or symbol
* @param {String} str An optional text to show in the loading label instead of the default one
*/
showLoading: function (str) {
var chart = this,
options = chart.options,
loadingDiv = chart.loadingDiv;
var loadingOptions = options.loading;
// create the layer at the first call
if (!loadingDiv) {
chart.loadingDiv = loadingDiv = createElement(DIV, {
className: PREFIX + 'loading'
}, extend(loadingOptions.style, {
zIndex: 10,
display: NONE
}), chart.container);
chart.loadingSpan = createElement(
'span',
null,
loadingOptions.labelStyle,
loadingDiv
);
}
// update text
chart.loadingSpan.innerHTML = str || options.lang.loading;
// show it
if (!chart.loadingShown) {
css(loadingDiv, {
opacity: 0,
display: '',
left: chart.plotLeft + PX,
top: chart.plotTop + PX,
width: chart.plotWidth + PX,
height: chart.plotHeight + PX
});
animate(loadingDiv, {
opacity: loadingOptions.style.opacity
}, {
duration: loadingOptions.showDuration || 0
});
chart.loadingShown = true;
}
},
/**
* Hide the loading layer
*/
hideLoading: function () {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
animate(loadingDiv, {
opacity: 0
}, {
duration: options.loading.hideDuration || 100,
complete: function () {
css(loadingDiv, { display: NONE });
}
});
}
this.loadingShown = false;
},
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
get: function (id) {
var chart = this,
axes = chart.axes,
series = chart.series;
var i,
j,
points;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id === id) {
return axes[i];
}
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id === id) {
return series[i];
}
}
// search points
for (i = 0; i < series.length; i++) {
points = series[i].points || [];
for (j = 0; j < points.length; j++) {
if (points[j].id === id) {
return points[j];
}
}
}
return null;
},
/**
* Create the Axis instances based on the config options
*/
getAxes: function () {
var chart = this,
options = this.options,
xAxisOptions = options.xAxis = splat(options.xAxis || {}),
yAxisOptions = options.yAxis = splat(options.yAxis || {}),
optionsArray,
axis;
// make sure the options are arrays and add some members
each(xAxisOptions, function (axis, i) {
axis.index = i;
axis.isX = true;
});
each(yAxisOptions, function (axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
optionsArray = xAxisOptions.concat(yAxisOptions);
each(optionsArray, function (axisOptions) {
axis = new Axis(chart, axisOptions);
});
chart.adjustTickAmounts();
},
/**
* Get the currently selected points from all series
*/
getSelectedPoints: function () {
var points = [];
each(this.series, function (serie) {
points = points.concat(grep(serie.points || [], function (point) {
return point.selected;
}));
});
return points;
},
/**
* Get the currently selected series
*/
getSelectedSeries: function () {
return grep(this.series, function (serie) {
return serie.selected;
});
},
/**
* Generate stacks for each series and calculate stacks total values
*/
getStacks: function () {
var chart = this;
// reset stacks for each yAxis
each(chart.yAxis, function (axis) {
if (axis.stacks && axis.hasVisibleSeries) {
axis.oldStacks = axis.stacks;
}
});
each(chart.series, function (series) {
if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
series.stackKey = series.type + pick(series.options.stack, '');
}
});
},
/**
* Display the zoom button
*/
showResetZoom: function () {
var chart = this,
lang = defaultOptions.lang,
btnOptions = chart.options.chart.resetZoomButton,
theme = btnOptions.theme,
states = theme.states,
alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.add()
.align(btnOptions.position, false, alignTo);
},
/**
* Zoom out to 1:1
*/
zoomOut: function () {
var chart = this;
fireEvent(chart, 'selection', { resetSelection: true }, function () {
chart.zoom();
});
},
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
zoom: function (event) {
var chart = this,
hasZoomed,
pointer = chart.pointer,
displayButton = false,
resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
each(chart.axes, function (axis) {
hasZoomed = axis.zoom();
});
} else { // else, zoom in on all axes
each(event.xAxis.concat(event.yAxis), function (axisData) {
var axis = axisData.axis,
isXAxis = axis.isXAxis;
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
} else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(
pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
);
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is called
* on mouse move, and the distance to pan is computed from chartX compared to
* the first chartX position in the dragging operation.
*/
pan: function (e, panning) {
var chart = this,
hoverPoints = chart.hoverPoints,
doRedraw;
// remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
var mousePos = e[isX ? 'chartX' : 'chartY'],
axis = chart[isX ? 'xAxis' : 'yAxis'][0],
startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
halfPointRange = (axis.pointRange || 0) / 2,
extremes = axis.getExtremes(),
newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange;
if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) {
axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
doRedraw = true;
}
chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, { cursor: 'move' });
},
/**
* Show the title and subtitle of the chart
*
* @param titleOptions {Object} New title options
* @param subtitleOptions {Object} New subtitle options
*
*/
setTitle: function (titleOptions, subtitleOptions) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function (arr) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': PREFIX + name,
zIndex: chartTitleOptions.zIndex || 4
})
.css(chartTitleOptions.style)
.add();
}
});
chart.layOutTitles();
},
/**
* Lay out the chart titles and cache the full offset height for use in getMargins
*/
layOutTitles: function () {
var titleOffset = 0,
title = this.title,
subtitle = this.subtitle,
options = this.options,
titleOptions = options.title,
subtitleOptions = options.subtitle,
autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
if (title) {
title
.css({ width: (titleOptions.width || autoWidth) + PX })
.align(extend({ y: 15 }, titleOptions), false, 'spacingBox');
if (!titleOptions.floating && !titleOptions.verticalAlign) {
titleOffset = title.getBBox().height;
// Adjust for browser consistency + backwards compat after #776 fix
if (titleOffset >= 18 && titleOffset <= 25) {
titleOffset = 15;
}
}
}
if (subtitle) {
subtitle
.css({ width: (subtitleOptions.width || autoWidth) + PX })
.align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox');
if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
}
}
this.titleOffset = titleOffset; // used in getMargins
},
/**
* Get chart width and height according to options and container size
*/
getChartSize: function () {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderToClone || chart.renderTo;
// get inner width and height from jQuery (#824)
chart.containerWidth = adapterRun(renderTo, 'width');
chart.containerHeight = adapterRun(renderTo, 'height');
chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460
chart.chartHeight = mathMax(0, pick(optionsChart.height,
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
chart.containerHeight > 19 ? chart.containerHeight : 400));
},
/**
* Create a clone of the chart's renderTo div and place it outside the viewport to allow
* size computation on chart.render and chart.redraw
*/
cloneRenderTo: function (revert) {
var clone = this.renderToClone,
container = this.container;
// Destroy the clone and bring the container back to the real renderTo div
if (revert) {
if (clone) {
this.renderTo.appendChild(container);
discardElement(clone);
delete this.renderToClone;
}
// Set up the clone
} else {
if (container && container.parentNode === this.renderTo) {
this.renderTo.removeChild(container); // do not clone this
}
this.renderToClone = clone = this.renderTo.cloneNode(0);
css(clone, {
position: ABSOLUTE,
top: '-9999px',
display: 'block' // #833
});
doc.body.appendChild(clone);
if (container) {
clone.appendChild(container);
}
}
},
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
getContainer: function () {
var chart = this,
container,
optionsChart = chart.options.chart,
chartWidth,
chartHeight,
renderTo,
indexAttrName = 'data-highcharts-chart',
oldChartIndex,
containerId;
chart.renderTo = renderTo = optionsChart.renderTo;
containerId = PREFIX + idCounter++;
if (isString(renderTo)) {
chart.renderTo = renderTo = doc.getElementById(renderTo);
}
// Display an error if the renderTo is wrong
if (!renderTo) {
error(13, true);
}
// If the container already holds a chart, destroy it
oldChartIndex = pInt(attr(renderTo, indexAttrName));
if (!isNaN(oldChartIndex) && charts[oldChartIndex]) {
charts[oldChartIndex].destroy();
}
// Make a reference to the chart from the div
attr(renderTo, indexAttrName, chart.index);
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly
if (!renderTo.offsetWidth) {
chart.cloneRenderTo();
}
// get the width and height
chart.getChartSize();
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// create the inner container
chart.container = container = createElement(DIV, {
className: PREFIX + 'container' +
(optionsChart.className ? ' ' + optionsChart.className : ''),
id: containerId
}, extend({
position: RELATIVE,
overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
// content overflow in IE
width: chartWidth + PX,
height: chartHeight + PX,
textAlign: 'left',
lineHeight: 'normal', // #427
zIndex: 0, // #1072
'-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
}, optionsChart.style),
chart.renderToClone || renderTo
);
// cache the cursor (#1650)
chart._cursor = container.style.cursor;
chart.renderer =
optionsChart.forExport ? // force SVG, used for SVG export
new SVGRenderer(container, chartWidth, chartHeight, true) :
new Renderer(container, chartWidth, chartHeight);
if (useCanVG) {
// If we need canvg library, extend and configure the renderer
// to get the tracker for translating mouse events
chart.renderer.create(chart, container, chartWidth, chartHeight);
}
},
/**
* Calculate margins by rendering axis labels in a preliminary position. Title,
* subtitle and legend have already been rendered at this stage, but will be
* moved into their final positions
*/
getMargins: function () {
var chart = this,
spacing = chart.spacing,
axisOffset,
legend = chart.legend,
margin = chart.margin,
legendOptions = chart.options.legend,
legendMargin = pick(legendOptions.margin, 10),
legendX = legendOptions.x,
legendY = legendOptions.y,
align = legendOptions.align,
verticalAlign = legendOptions.verticalAlign,
titleOffset = chart.titleOffset;
chart.resetMargins();
axisOffset = chart.axisOffset;
// Adjust for title and subtitle
if (titleOffset && !defined(margin[0])) {
chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
}
// Adjust for legend
if (legend.display && !legendOptions.floating) {
if (align === 'right') { // horizontal alignment handled first
if (!defined(margin[1])) {
chart.marginRight = mathMax(
chart.marginRight,
legend.legendWidth - legendX + legendMargin + spacing[1]
);
}
} else if (align === 'left') {
if (!defined(margin[3])) {
chart.plotLeft = mathMax(
chart.plotLeft,
legend.legendWidth + legendX + legendMargin + spacing[3]
);
}
} else if (verticalAlign === 'top') {
if (!defined(margin[0])) {
chart.plotTop = mathMax(
chart.plotTop,
legend.legendHeight + legendY + legendMargin + spacing[0]
);
}
} else if (verticalAlign === 'bottom') {
if (!defined(margin[2])) {
chart.marginBottom = mathMax(
chart.marginBottom,
legend.legendHeight - legendY + legendMargin + spacing[2]
);
}
}
}
// adjust for scroller
if (chart.extraBottomMargin) {
chart.marginBottom += chart.extraBottomMargin;
}
if (chart.extraTopMargin) {
chart.plotTop += chart.extraTopMargin;
}
// pre-render axes to get labels offset width
if (chart.hasCartesianSeries) {
each(chart.axes, function (axis) {
axis.getOffset();
});
}
if (!defined(margin[3])) {
chart.plotLeft += axisOffset[3];
}
if (!defined(margin[0])) {
chart.plotTop += axisOffset[0];
}
if (!defined(margin[2])) {
chart.marginBottom += axisOffset[2];
}
if (!defined(margin[1])) {
chart.marginRight += axisOffset[1];
}
chart.setChartSize();
},
/**
* Add the event handlers necessary for auto resizing
*
*/
initReflow: function () {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderTo,
reflowTimeout;
function reflow(e) {
var width = optionsChart.width || adapterRun(renderTo, 'width'),
height = optionsChart.height || adapterRun(renderTo, 'height'),
target = e ? e.target : win; // #805 - MooTools doesn't supply e
// Width and height checks for display:none. Target is doc in IE8 and Opera,
// win in Firefox, Chrome and IE9.
if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
if (width !== chart.containerWidth || height !== chart.containerHeight) {
clearTimeout(reflowTimeout);
chart.reflowTimeout = reflowTimeout = setTimeout(function () {
if (chart.container) { // It may have been destroyed in the meantime (#1257)
chart.setSize(width, height, false);
chart.hasUserSize = null;
}
}, 100);
}
chart.containerWidth = width;
chart.containerHeight = height;
}
}
chart.reflow = reflow;
addEvent(win, 'resize', reflow);
addEvent(chart, 'destroy', function () {
removeEvent(win, 'resize', reflow);
});
},
/**
* Resize the chart to a given width and height
* @param {Number} width
* @param {Number} height
* @param {Object|Boolean} animation
*/
setSize: function (width, height, animation) {
var chart = this,
chartWidth,
chartHeight,
fireEndResize;
// Handle the isResizing counter
chart.isResizing += 1;
fireEndResize = function () {
if (chart) {
fireEvent(chart, 'endResize', null, function () {
chart.isResizing -= 1;
});
}
};
// set the animation for the current process
setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (defined(width)) {
chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
chart.hasUserSize = !!chartWidth;
}
if (defined(height)) {
chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
}
css(chart.container, {
width: chartWidth + PX,
height: chartHeight + PX
});
chart.setChartSize(true);
chart.renderer.setSize(chartWidth, chartHeight, animation);
// handle axes
chart.maxTicks = null;
each(chart.axes, function (axis) {
axis.isDirty = true;
axis.setScale();
});
// make sure non-cartesian series are also handled
each(chart.series, function (serie) {
serie.isDirty = true;
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.getMargins();
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// fire endResize and set isResizing back
// If animation is disabled, fire without delay
if (globalAnimation === false) {
fireEndResize();
} else { // else set a timeout with the animation duration
setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
}
},
/**
* Set the public chart properties. This is done before and after the pre-render
* to determine margin sizes
*/
setChartSize: function (skipAxes) {
var chart = this,
inverted = chart.inverted,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
optionsChart = chart.options.chart,
spacing = chart.spacing,
clipOffset = chart.clipOffset,
clipX,
clipY,
plotLeft,
plotTop,
plotWidth,
plotHeight,
plotBorderWidth;
chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
chart.plotTop = plotTop = mathRound(chart.plotTop);
chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
chart.plotSizeX = inverted ? plotHeight : plotWidth;
chart.plotSizeY = inverted ? plotWidth : plotHeight;
chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
// Set boxes used for alignment
chart.spacingBox = renderer.spacingBox = {
x: spacing[3],
y: spacing[0],
width: chartWidth - spacing[3] - spacing[1],
height: chartHeight - spacing[0] - spacing[2]
};
chart.plotBox = renderer.plotBox = {
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
};
plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
chart.clipBox = {
x: clipX,
y: clipY,
width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)
};
if (!skipAxes) {
each(chart.axes, function (axis) {
axis.setAxisSize();
axis.setAxisTranslation();
});
}
},
/**
* Initial margins before auto size margins are applied
*/
resetMargins: function () {
var chart = this,
spacing = chart.spacing,
margin = chart.margin;
chart.plotTop = pick(margin[0], spacing[0]);
chart.marginRight = pick(margin[1], spacing[1]);
chart.marginBottom = pick(margin[2], spacing[2]);
chart.plotLeft = pick(margin[3], spacing[3]);
chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
chart.clipOffset = [0, 0, 0, 0];
},
/**
* Draw the borders and backgrounds for chart and plot area
*/
drawChartBox: function () {
var chart = this,
optionsChart = chart.options.chart,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartBackground = chart.chartBackground,
plotBackground = chart.plotBackground,
plotBorder = chart.plotBorder,
plotBGImage = chart.plotBGImage,
chartBorderWidth = optionsChart.borderWidth || 0,
chartBackgroundColor = optionsChart.backgroundColor,
plotBackgroundColor = optionsChart.plotBackgroundColor,
plotBackgroundImage = optionsChart.plotBackgroundImage,
plotBorderWidth = optionsChart.plotBorderWidth || 0,
mgn,
bgAttr,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
plotBox = chart.plotBox,
clipRect = chart.clipRect,
clipBox = chart.clipBox;
// Chart area
mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
if (chartBorderWidth || chartBackgroundColor) {
if (!chartBackground) {
bgAttr = {
fill: chartBackgroundColor || NONE
};
if (chartBorderWidth) { // #980
bgAttr.stroke = optionsChart.borderColor;
bgAttr['stroke-width'] = chartBorderWidth;
}
chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
optionsChart.borderRadius, chartBorderWidth)
.attr(bgAttr)
.add()
.shadow(optionsChart.shadow);
} else { // resize
chartBackground.animate(
chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn)
);
}
}
// Plot background
if (plotBackgroundColor) {
if (!plotBackground) {
chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
.attr({
fill: plotBackgroundColor
})
.add()
.shadow(optionsChart.plotShadow);
} else {
plotBackground.animate(plotBox);
}
}
if (plotBackgroundImage) {
if (!plotBGImage) {
chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
.add();
} else {
plotBGImage.animate(plotBox);
}
}
// Plot clip
if (!clipRect) {
chart.clipRect = renderer.clipRect(clipBox);
} else {
clipRect.animate({
width: clipBox.width,
height: clipBox.height
});
}
// Plot area border
if (plotBorderWidth) {
if (!plotBorder) {
chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
.attr({
stroke: optionsChart.plotBorderColor,
'stroke-width': plotBorderWidth,
zIndex: 1
})
.add();
} else {
plotBorder.animate(
plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight)
);
}
}
// reset
chart.isDirtyBox = false;
},
/**
* Detect whether a certain chart property is needed based on inspecting its options
* and series. This mainly applies to the chart.invert property, and in extensions to
* the chart.angular and chart.polar properties.
*/
propFromSeries: function () {
var chart = this,
optionsChart = chart.options.chart,
klass,
seriesOptions = chart.options.series,
i,
value;
each(['inverted', 'angular', 'polar'], function (key) {
// The default series type's class
klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
// Get the value from available chart-wide properties
value = (
chart[key] || // 1. it is set before
optionsChart[key] || // 2. it is set in the options
(klass && klass.prototype[key]) // 3. it's default series class requires it
);
// 4. Check if any the chart's series require it
i = seriesOptions && seriesOptions.length;
while (!value && i--) {
klass = seriesTypes[seriesOptions[i].type];
if (klass && klass.prototype[key]) {
value = true;
}
}
// Set the chart property
chart[key] = value;
});
},
/**
* Link two or more series together. This is done initially from Chart.render,
* and after Chart.addSeries and Series.remove.
*/
linkSeries: function () {
var chart = this,
chartSeries = chart.series;
// Reset links
each(chartSeries, function (series) {
series.linkedSeries.length = 0;
});
// Apply new links
each(chartSeries, function (series) {
var linkedTo = series.options.linkedTo;
if (isString(linkedTo)) {
if (linkedTo === ':previous') {
linkedTo = chart.series[series.index - 1];
} else {
linkedTo = chart.get(linkedTo);
}
if (linkedTo) {
linkedTo.linkedSeries.push(series);
series.linkedParent = linkedTo;
}
}
});
},
/**
* Render all graphics for the chart
*/
render: function () {
var chart = this,
axes = chart.axes,
renderer = chart.renderer,
options = chart.options;
var labels = options.labels,
credits = options.credits,
creditsHref;
// Title
chart.setTitle();
// Legend
chart.legend = new Legend(chart, options.legend);
chart.getStacks(); // render stacks
// Get margins by pre-rendering axes
// set axes scales
each(axes, function (axis) {
axis.setScale();
});
chart.getMargins();
chart.maxTicks = null; // reset for second pass
each(axes, function (axis) {
axis.setTickPositions(true); // update to reflect the new margins
axis.setMaxTicks();
});
chart.adjustTickAmounts();
chart.getMargins(); // second pass to check for new labels
// Draw the borders and backgrounds
chart.drawChartBox();
// Axes
if (chart.hasCartesianSeries) {
each(axes, function (axis) {
axis.render();
});
}
// The series
if (!chart.seriesGroup) {
chart.seriesGroup = renderer.g('series-group')
.attr({ zIndex: 3 })
.add();
}
each(chart.series, function (serie) {
serie.translate();
serie.setTooltipPoints();
serie.render();
});
// Labels
if (labels.items) {
each(labels.items, function (label) {
var style = extend(labels.style, label.style),
x = pInt(style.left) + chart.plotLeft,
y = pInt(style.top) + chart.plotTop + 12;
// delete to prevent rewriting in IE
delete style.left;
delete style.top;
renderer.text(
label.html,
x,
y
)
.attr({ zIndex: 2 })
.css(style)
.add();
});
}
// Credits
if (credits.enabled && !chart.credits) {
creditsHref = credits.href;
chart.credits = renderer.text(
credits.text,
0,
0
)
.on('click', function () {
if (creditsHref) {
location.href = creditsHref;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.css(credits.style)
.add()
.align(credits.position);
}
// Set flag
chart.hasRendered = true;
},
/**
* Clean up memory usage
*/
destroy: function () {
var chart = this,
axes = chart.axes,
series = chart.series,
container = chart.container,
i,
parentNode = container && container.parentNode;
// fire the chart.destoy event
fireEvent(chart, 'destroy');
// Delete the chart from charts lookup array
charts[chart.index] = UNDEFINED;
chart.renderTo.removeAttribute('data-highcharts-chart');
// remove events
removeEvent(chart);
// ==== Destroy collections:
// Destroy axes
i = axes.length;
while (i--) {
axes[i] = axes[i].destroy();
}
// Destroy each series
i = series.length;
while (i--) {
series[i] = series[i].destroy();
}
// ==== Destroy chart properties:
each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
var prop = chart[name];
if (prop && prop.destroy) {
chart[name] = prop.destroy();
}
});
// remove container and all SVG
if (container) { // can break in IE when destroyed before finished loading
container.innerHTML = '';
removeEvent(container);
if (parentNode) {
discardElement(container);
}
}
// clean it all up
for (i in chart) {
delete chart[i];
}
},
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*/
isReadyToRender: function () {
var chart = this;
// Note: in spite of JSLint's complaints, win == win.top is required
/*jslint eqeq: true*/
if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
/*jslint eqeq: false*/
if (useCanVG) {
// Delay rendering until canvg library is downloaded and ready
CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
} else {
doc.attachEvent('onreadystatechange', function () {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
}
return false;
}
return true;
},
/**
* Prepare for first rendering after all data are loaded
*/
firstRender: function () {
var chart = this,
options = chart.options,
callback = chart.callback;
// Check whether the chart is ready to render
if (!chart.isReadyToRender()) {
return;
}
// Create the container
chart.getContainer();
// Run an early event after the container and renderer are established
fireEvent(chart, 'init');
chart.resetMargins();
chart.setChartSize();
// Set the common chart properties (mainly invert) from the given series
chart.propFromSeries();
// get axes
chart.getAxes();
// Initialize the series
each(options.series || [], function (serieOptions) {
chart.initSeries(serieOptions);
});
chart.linkSeries();
// Run an event after axes and series are initialized, but before render. At this stage,
// the series data is indexed and cached in the xData and yData arrays, so we can access
// those before rendering. Used in Highstock.
fireEvent(chart, 'beforeRender');
// depends on inverted and on margins being set
chart.pointer = new Pointer(chart, options);
chart.render();
// add canvas
chart.renderer.draw();
// run callbacks
if (callback) {
callback.apply(chart, [chart]);
}
each(chart.callbacks, function (fn) {
fn.apply(chart, [chart]);
});
// If the chart was rendered outside the top container, put it back in
chart.cloneRenderTo(true);
fireEvent(chart, 'load');
},
/**
* Creates arrays for spacing and margin from given options.
*/
splashArray: function (target, options) {
var oVar = options[target],
tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
return [pick(options[target + 'Top'], tArray[0]),
pick(options[target + 'Right'], tArray[1]),
pick(options[target + 'Bottom'], tArray[2]),
pick(options[target + 'Left'], tArray[3])];
}
}; // end Chart
// Hook for exporting module
Chart.prototype.callbacks = [];
/**
* The Point object and prototype. Inheritable and used as base for PiePoint
*/
var Point = function () {};
Point.prototype = {
/**
* Initialize the point
* @param {Object} series The series object containing this point
* @param {Object} options The data in either number, array or object format
*/
init: function (series, options, x) {
var point = this,
colors;
point.series = series;
point.applyOptions(options, x);
point.pointAttr = {};
if (series.options.colorByPoint) {
colors = series.options.colors || series.chart.options.colors;
point.color = point.color || colors[series.colorCounter++];
// loop back to zero
if (series.colorCounter === colors.length) {
series.colorCounter = 0;
}
}
series.chart.pointCount++;
return point;
},
/**
* Apply the options containing the x and y data and possible some extra properties.
* This is called on point init or from point.update.
*
* @param {Object} options
*/
applyOptions: function (options, x) {
var point = this,
series = point.series,
pointValKey = series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
if (pointValKey) {
point.y = point[pointValKey];
}
// If no x is set by now, get auto incremented value. All points must have an
// x value, however the y value can be null to create a gap in the series
if (point.x === UNDEFINED && series) {
point.x = x === UNDEFINED ? series.autoIncrement() : x;
}
return point;
},
/**
* Transform number or array configs into objects
*/
optionsToObject: function (options) {
var ret = {},
series = this.series,
pointArrayMap = series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
firstItemType,
i = 0,
j = 0;
if (typeof options === 'number' || options === null) {
ret[pointArrayMap[0]] = options;
} else if (isArray(options)) {
// with leading x value
if (options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
} else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
ret[pointArrayMap[j++]] = options[i++];
}
} else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point dataLabels that need
// to be considered in drawDataLabels. These can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
},
/**
* Destroy a point to clear memory. Its reference still stays in series.data.
*/
destroy: function () {
var point = this,
series = point.series,
chart = series.chart,
hoverPoints = chart.hoverPoints,
prop;
chart.pointCount--;
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// remove all events
if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
removeEvent(point);
point.destroyElements();
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
for (prop in point) {
point[prop] = null;
}
},
/**
* Destroy SVG elements associated with the point
*/
destroyElements: function () {
var point = this,
props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
prop,
i = 6;
while (i--) {
prop = props[i];
if (point[prop]) {
point[prop] = point[prop].destroy();
}
}
},
/**
* Return the configuration hash needed for the data label and tooltip formatters
*/
getLabelConfig: function () {
var point = this;
return {
x: point.category,
y: point.y,
key: point.name || point.category,
series: point.series,
point: point,
percentage: point.percentage,
total: point.total || point.stackTotal
};
},
/**
* Toggle the selection status of a point
* @param {Boolean} selected Whether to select or unselect the point.
* @param {Boolean} accumulate Whether to add to the previous selection. By default,
* this happens if the control key (Cmd on Mac) was pressed during clicking.
*/
select: function (selected, accumulate) {
var point = this,
series = point.series,
chart = series.chart;
selected = pick(selected, !point.selected);
// fire the event with the defalut handler
point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
point.selected = point.options.selected = selected;
series.options.data[inArray(point, series.data)] = point.options;
point.setState(selected && SELECT_STATE);
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
each(chart.getSelectedPoints(), function (loopPoint) {
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected = false;
series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
loopPoint.setState(NORMAL_STATE);
loopPoint.firePointEvent('unselect');
}
});
}
});
},
/**
* Runs on mouse over the point
*/
onMouseOver: function (e) {
var point = this,
series = point.series,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// set normal state to previous series
if (hoverPoint && hoverPoint !== point) {
hoverPoint.onMouseOut();
}
// trigger the event
point.firePointEvent('mouseOver');
// update the tooltip
if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.refresh(point, e);
}
// hover this
point.setState(HOVER_STATE);
chart.hoverPoint = point;
},
/**
* Runs on mouse out from the point
*/
onMouseOut: function () {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887
this.firePointEvent('mouseOut');
this.setState();
chart.hoverPoint = null;
}
},
/**
* Extendable method for formatting each point's tooltip line
*
* @return {String} A string to be concatenated in to the common tooltip text
*/
tooltipFormatter: function (pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series,
seriesTooltipOptions = series.tooltipOptions,
valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
valuePrefix = seriesTooltipOptions.valuePrefix || '',
valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Loop over the point array map and replace unformatted values with sprintf formatting markup
each(series.pointArrayMap || ['y'], function (key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
});
},
/**
* Update the point with new options (typically x/y data) and optionally redraw the series.
*
* @param {Object} options Point options as defined in the series.data array
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
*/
update: function (options, redraw, animation) {
var point = this,
series = point.series,
graphic = point.graphic,
i,
data = series.data,
chart = series.chart,
seriesOptions = series.options;
redraw = pick(redraw, true);
// fire the event with a default handler of doing the update
point.firePointEvent('update', { options: options }, function () {
point.applyOptions(options);
// update visuals
if (isObject(options)) {
series.getAttribs();
if (graphic) {
if (options && options.marker && options.marker.symbol) {
point.graphic = graphic.destroy();
} else {
graphic.attr(point.pointAttr[point.state || '']);
}
}
}
// record changes in the parallel arrays
i = inArray(point, data);
series.xData[i] = point.x;
series.yData[i] = series.toYData ? series.toYData(point) : point.y;
series.zData[i] = point.z;
seriesOptions.data[i] = point.options;
// redraw
series.isDirty = series.isDirtyData = true;
if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
chart.isDirtyBox = true;
}
if (seriesOptions.legendType === 'point') { // #1831, #1885
chart.legend.destroyItem(point);
}
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Remove a point and optionally redraw the series and if necessary the axes
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
var point = this,
series = point.series,
points = series.points,
chart = series.chart,
i,
data = series.data;
setAnimation(animation, chart);
redraw = pick(redraw, true);
// fire the event with a default handler of removing the point
point.firePointEvent('remove', null, function () {
// splice all the parallel arrays
i = inArray(point, data);
if (data.length === points.length) {
points.splice(i, 1);
}
data.splice(i, 1);
series.options.data.splice(i, 1);
series.xData.splice(i, 1);
series.yData.splice(i, 1);
series.zData.splice(i, 1);
point.destroy();
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw();
}
});
},
/**
* Fire an event on the Point object. Must not be renamed to fireEvent, as this
* causes a name clash in MooTools
* @param {String} eventType
* @param {Object} eventArgs Additional event arguments
* @param {Function} defaultFunction Default event handler
*/
firePointEvent: function (eventType, eventArgs, defaultFunction) {
var point = this,
series = this.series,
seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
this.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function (event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
};
}
fireEvent(this, eventType, eventArgs, defaultFunction);
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*/
importEvents: function () {
if (!this.hasImportedEvents) {
var point = this,
options = merge(point.series.options.point, point.options),
events = options.events,
eventType;
point.events = events;
for (eventType in events) {
addEvent(point, eventType, events[eventType]);
}
this.hasImportedEvents = true;
}
},
/**
* Set the point's state
* @param {String} state
*/
setState: function (state) {
var point = this,
plotX = point.plotX,
plotY = point.plotY,
series = point.series,
stateOptions = series.options.states,
markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
normalDisabled = markerOptions && !markerOptions.enabled,
markerStateOptions = markerOptions && markerOptions.states[state],
stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
stateMarkerGraphic = series.stateMarkerGraphic,
pointMarker = point.marker || {},
chart = series.chart,
radius,
newSymbol,
pointAttr = point.pointAttr;
state = state || NORMAL_STATE; // empty string
if (
// already has this state
state === point.state ||
// selected points don't respond to hover
(point.selected && state !== SELECT_STATE) ||
// series' state options is disabled
(stateOptions[state] && stateOptions[state].enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) ||
// individual point marker's state options is disabled
(state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
) {
return;
}
// apply hover styles to the existing point
if (point.graphic) {
radius = markerOptions && point.graphic.symbolName && pointAttr[state].r;
point.graphic.attr(merge(
pointAttr[state],
radius ? { // new symbol attributes (#507, #612)
x: plotX - radius,
y: plotY - radius,
width: 2 * radius,
height: 2 * radius
} : {}
));
} else {
// if a graphic is not applied to each point in the normal state, create a shared
// graphic for the hover state
if (state && markerStateOptions) {
radius = markerStateOptions.radius;
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw away the
// state marker graphic and force a new one (#1459)
if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (!stateMarkerGraphic) {
series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
newSymbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius
)
.attr(pointAttr[state])
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
// Move the existing graphic
} else {
stateMarkerGraphic.attr({ // #1054
x: plotX - radius,
y: plotY - radius
});
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide']();
}
}
point.state = state;
}
};
/**
* @classDescription The base function which all other series types inherit from. The data in the series is stored
* in various arrays.
*
* - First, series.options.data contains all the original config options for
* each point whether added by options or methods like series.addPoint.
* - Next, series.data contains those values converted to points, but in case the series data length
* exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
* only contains the points that have been created on demand.
* - Then there's series.points that contains all currently visible point objects. In case of cropping,
* the cropped-away points are not part of this array. The series.points array starts at series.cropStart
* compared to series.data and series.options.data. If however the series data is grouped, these can't
* be correlated one to one.
* - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
* - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
*
* @param {Object} chart
* @param {Object} options
*/
var Series = function () {};
Series.prototype = {
isCartesian: true,
type: 'line',
pointClass: Point,
sorted: true, // requires the data to be sorted
requireSorting: true,
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'lineColor',
'stroke-width': 'lineWidth',
fill: 'fillColor',
r: 'radius'
},
colorCounter: 0,
init: function (chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series;
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: NORMAL_STATE,
pointAttr: {},
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// special
if (useCanVG) {
options.animation = false;
}
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// set the data
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123)
stableSort(chartSeries, function (a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, a._i);
});
each(chartSeries, function (series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
},
/**
* Set the xAxis and yAxis properties of cartesian series, and register the series
* in the axis.series array
*/
bindAxes: function () {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
if (series.isCartesian) {
each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function (axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS]) {
error(18, true);
}
});
}
},
/**
* Return an auto incremented x value based on the pointStart and pointInterval options.
* This is only used if an x value is not given for the point that calls autoIncrement.
*/
autoIncrement: function () {
var series = this,
options = series.options,
xIncrement = series.xIncrement;
xIncrement = pick(xIncrement, options.pointStart, 0);
series.pointInterval = pick(series.pointInterval, options.pointInterval, 1);
series.xIncrement = xIncrement + series.pointInterval;
return xIncrement;
},
/**
* Divide the series data into segments divided by null values.
*/
getSegments: function () {
var series = this,
lastNull = -1,
segments = [],
i,
points = series.points,
pointsLength = points.length;
if (pointsLength) { // no action required for []
// if connect nulls, just remove null points
if (series.options.connectNulls) {
i = pointsLength;
while (i--) {
if (points[i].y === null) {
points.splice(i, 1);
}
}
if (points.length) {
segments = [points];
}
// else, split on null points
} else {
each(points, function (point, i) {
if (point.y === null) {
if (i > lastNull + 1) {
segments.push(points.slice(lastNull + 1, i));
}
lastNull = i;
} else if (i === pointsLength - 1) { // last value
segments.push(points.slice(lastNull + 1, i + 1));
}
});
}
}
// register it
series.segments = segments;
},
/**
* Set the series options by merging from the options tree
* @param {Object} itemOptions
*/
setOptions: function (itemOptions) {
var chart = this.chart,
chartOptions = chart.options,
plotOptions = chartOptions.plotOptions,
typeOptions = plotOptions[this.type],
options;
this.userOptions = itemOptions;
options = merge(
typeOptions,
plotOptions.series,
itemOptions
);
// the tooltip options are merged between global and series specific options
this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip);
// Delte marker object if not allowed (#1125)
if (typeOptions.marker === null) {
delete options.marker;
}
return options;
},
/**
* Get the series' color
*/
getColor: function () {
var options = this.options,
userOptions = this.userOptions,
defaultColors = this.chart.options.colors,
counters = this.chart.counters,
color,
colorIndex;
color = options.color || defaultPlotOptions[this.type].color;
if (!color && !options.colorByPoint) {
if (defined(userOptions._colorIndex)) { // after Series.update()
colorIndex = userOptions._colorIndex;
} else {
userOptions._colorIndex = counters.color;
colorIndex = counters.color++;
}
color = defaultColors[colorIndex];
}
this.color = color;
counters.wrapColor(defaultColors.length);
},
/**
* Get the series' symbol
*/
getSymbol: function () {
var series = this,
userOptions = series.userOptions,
seriesMarkerOption = series.options.marker,
chart = series.chart,
defaultSymbols = chart.options.symbols,
counters = chart.counters,
symbolIndex;
series.symbol = seriesMarkerOption.symbol;
if (!series.symbol) {
if (defined(userOptions._symbolIndex)) { // after Series.update()
symbolIndex = userOptions._symbolIndex;
} else {
userOptions._symbolIndex = counters.symbol;
symbolIndex = counters.symbol++;
}
series.symbol = defaultSymbols[symbolIndex];
}
// don't substract radius in image symbols (#604)
if (/^url/.test(series.symbol)) {
seriesMarkerOption.radius = 0;
}
counters.wrapSymbol(defaultSymbols.length);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLegendSymbol: function (legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendOptions = legend.options,
legendSymbol,
symbolWidth = legendOptions.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3),
attr;
// Draw the line
if (options.lineWidth) {
attr = {
'stroke-width': options.lineWidth
};
if (options.dashStyle) {
attr.dashstyle = options.dashStyle;
}
this.legendLine = renderer.path([
M,
0,
verticalCenter,
L,
symbolWidth,
verticalCenter
])
.attr(attr)
.add(legendItemGroup);
}
// Draw the marker
if (markerOptions && markerOptions.enabled) {
radius = markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius
)
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
},
/**
* Add a point dynamically after chart load time
* @param {Object} options Point options as given in series.data
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean} shift If shift is true, a point is shifted off the start
* of the series as one is appended to the end.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
addPoint: function (options, redraw, shift, animation) {
var series = this,
seriesOptions = series.options,
data = series.data,
graph = series.graph,
area = series.area,
chart = series.chart,
xData = series.xData,
yData = series.yData,
zData = series.zData,
names = series.xAxis && series.xAxis.names,
currentShift = (graph && graph.shift) || 0,
dataOptions = seriesOptions.data,
point,
isInTheMiddle,
x,
i;
setAnimation(animation, chart);
// Make graph animate sideways
if (shift) {
each([graph, area, series.graphNeg, series.areaNeg], function (shape) {
if (shape) {
shape.shift = currentShift + 1;
}
});
}
if (area) {
area.isArea = true; // needed in animation, both with and without shift
}
// Optional redraw, defaults to true
redraw = pick(redraw, true);
// Get options and push the point to xData, yData and series.options. In series.generatePoints
// the Point instance will be created on demand and pushed to the series.data array.
point = { series: series };
series.pointClass.prototype.applyOptions.apply(point, [options]);
x = point.x;
// Get the insertion point
i = xData.length;
if (series.requireSorting && x < xData[i - 1]) {
isInTheMiddle = true;
while (i && xData[i - 1] > x) {
i--;
}
}
xData.splice(i, 0, x);
yData.splice(i, 0, series.toYData ? series.toYData(point) : point.y);
zData.splice(i, 0, point.z);
if (names) {
names[x] = point.name;
}
dataOptions.splice(i, 0, options);
if (isInTheMiddle) {
series.data.splice(i, 0, null);
series.processData();
}
// Generate points to be added to the legend (#1329)
if (seriesOptions.legendType === 'point') {
series.generatePoints();
}
// Shift the first point off the parallel arrays
// todo: consider series.removePoint(i) method
if (shift) {
if (data[0] && data[0].remove) {
data[0].remove(false);
} else {
data.shift();
xData.shift();
yData.shift();
zData.shift();
dataOptions.shift();
}
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
series.getAttribs(); // #1937
chart.redraw();
}
},
/**
* Replace the series data with a new set of data
* @param {Object} data
* @param {Object} redraw
*/
setData: function (data, redraw) {
var series = this,
oldData = series.points,
options = series.options,
chart = series.chart,
firstPoint = null,
xAxis = series.xAxis,
names = xAxis && xAxis.names,
i;
// reset properties
series.xIncrement = null;
series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange;
series.colorCounter = 0; // for series with colorByPoint (#1547)
// parallel arrays
var xData = [],
yData = [],
zData = [],
dataLength = data ? data.length : [],
turboThreshold = pick(options.turboThreshold, 1000),
pt,
pointArrayMap = series.pointArrayMap,
valueCount = pointArrayMap && pointArrayMap.length,
hasToYData = !!series.toYData;
// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
// first value is tested, and we assume that all the rest are defined the same
// way. Although the 'for' loops are similar, they are repeated inside each
// if-else conditional for max performance.
if (turboThreshold && dataLength > turboThreshold) {
// find the first non-null point
i = 0;
while (firstPoint === null && i < dataLength) {
firstPoint = data[i];
i++;
}
if (isNumber(firstPoint)) { // assume all points are numbers
var x = pick(options.pointStart, 0),
pointInterval = pick(options.pointInterval, 1);
for (i = 0; i < dataLength; i++) {
xData[i] = x;
yData[i] = data[i];
x += pointInterval;
}
series.xIncrement = x;
} else if (isArray(firstPoint)) { // assume all points are arrays
if (valueCount) { // [x, low, high] or [x, o, h, l, c]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt.slice(1, valueCount + 1);
}
} else { // [x, y]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt[1];
}
}
} else {
error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
}
} else {
for (i = 0; i < dataLength; i++) {
if (data[i] !== UNDEFINED) { // stray commas in oldIE
pt = { series: series };
series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
xData[i] = pt.x;
yData[i] = hasToYData ? series.toYData(pt) : pt.y;
zData[i] = pt.z;
if (names && pt.name) {
names[pt.x] = pt.name; // #2046
}
}
}
}
// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
if (isString(yData[0])) {
error(14, true);
}
series.data = [];
series.options.data = data;
series.xData = xData;
series.yData = yData;
series.zData = zData;
// destroy old points
i = (oldData && oldData.length) || 0;
while (i--) {
if (oldData[i] && oldData[i].destroy) {
oldData[i].destroy();
}
}
// reset minRange (#878)
if (xAxis) {
xAxis.minRange = xAxis.userMinRange;
}
// redraw
series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw(false);
}
},
/**
* Remove a series and optionally redraw the chart
*
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
var series = this,
chart = series.chart;
redraw = pick(redraw, true);
if (!series.isRemoving) { /* prevent triggering native event in jQuery
(calling the remove function from the remove event) */
series.isRemoving = true;
// fire the event with a default handler of removing the point
fireEvent(series, 'remove', null, function () {
// destroy elements
series.destroy();
// redraw
chart.isDirtyLegend = chart.isDirtyBox = true;
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
series.isRemoving = false;
},
/**
* Process the data by cropping away unused data points if the series is longer
* than the crop threshold. This saves computing time for lage series.
*/
processData: function (force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
isCartesian = series.isCartesian;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
var min = xAxis.min,
max = xAxis.max;
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
}
}
// Find the closest distance between processed points
for (i = processedXData.length - 1; i >= 0; i--) {
distance = processedXData[i] - processedXData[i - 1];
if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
series.pointRange = closestPointRange || 1;
}
series.closestPointRange = closestPointRange;
},
/**
* Iterate over xData and crop values between min and max. Returns object containing crop start/end
* cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
*/
cropData: function (xData, yData, min, max) {
var dataLength = xData.length,
cropStart = 0,
cropEnd = dataLength,
cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
i;
// iterate up to find slice start
for (i = 0; i < dataLength; i++) {
if (xData[i] >= min) {
cropStart = mathMax(0, i - cropShoulder);
break;
}
}
// proceed to find slice end
for (; i < dataLength; i++) {
if (xData[i] > max) {
cropEnd = i + cropShoulder;
break;
}
}
return {
xData: xData.slice(cropStart, cropEnd),
yData: yData.slice(cropStart, cropEnd),
start: cropStart,
end: cropEnd
};
},
/**
* Generate the data point after the data has been processed by cropping away
* unused points and optionally grouped in Highcharts Stock.
*/
generatePoints: function () {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
pointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== UNDEFINED) { // #970
data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
}
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = UNDEFINED; // #1003
}
}
}
series.data = data;
series.points = points;
},
/**
* Adds series' points value to corresponding stack
*/
setStackedPoints: function () {
if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
return;
}
var series = this,
xData = series.processedXData,
yData = series.processedYData,
stackedYData = [],
yDataLength = yData.length,
seriesOptions = series.options,
threshold = seriesOptions.threshold,
stackOption = seriesOptions.stack,
stacking = seriesOptions.stacking,
stackKey = series.stackKey,
negKey = '-' + stackKey,
negStacks = series.negStacks,
yAxis = series.yAxis,
stacks = yAxis.stacks,
oldStacks = yAxis.oldStacks,
isNegative,
stack,
other,
key,
i,
x,
y;
// loop over the non-null y values and read them into a local array
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// Read stacked values into a stack based on the x value,
// the sign of y and the stack key. Stacking is also handled for null values (#739)
isNegative = negStacks && y < threshold;
key = isNegative ? negKey : stackKey;
// Create empty object for this stack if it doesn't exist yet
if (!stacks[key]) {
stacks[key] = {};
}
// Initialize StackItem for this x
if (!stacks[key][x]) {
if (oldStacks[key] && oldStacks[key][x]) {
stacks[key][x] = oldStacks[key][x];
stacks[key][x].total = null;
} else {
stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption, stacking);
}
}
// If the StackItem doesn't exist, create it first
stack = stacks[key][x];
stack.points[series.index] = [stack.cum || 0];
// Add value to the stack total
if (stacking === 'percent') {
// Percent stacked column, totals are the same for the positive and negative stacks
other = isNegative ? stackKey : negKey;
if (negStacks && stacks[other] && stacks[other][x]) {
other = stacks[other][x];
stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
// Percent stacked areas
} else {
stack.total += mathAbs(y) || 0;
}
} else {
stack.total += y || 0;
}
stack.cum = (stack.cum || 0) + (y || 0);
stack.points[series.index].push(stack.cum);
stackedYData[i] = stack.cum;
}
if (stacking === 'percent') {
yAxis.usePercentage = true;
}
this.stackedYData = stackedYData; // To be used in getExtremes
// Reset old stacks
yAxis.oldStacks = {};
},
/**
* Iterate over all stacks and compute the absolute values to percent
*/
setPercentStacks: function () {
var series = this,
stackKey = series.stackKey,
stacks = series.yAxis.stacks;
each([stackKey, '-' + stackKey], function (key) {
var i = series.xData.length,
x,
stack,
pointExtremes,
totalFactor;
while (i--) {
x = series.xData[i];
stack = stacks[key] && stacks[key][x];
pointExtremes = stack && stack.points[series.index];
if (pointExtremes) {
totalFactor = stack.total ? 100 / stack.total : 0;
pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
series.stackedYData[i] = pointExtremes[1];
}
}
});
},
/**
* Calculate Y extremes for visible data
*/
getExtremes: function () {
var xAxis = this.xAxis,
yAxis = this.yAxis,
xData = this.processedXData,
yData = this.stackedYData || this.processedYData,
yDataLength = yData.length,
activeYData = [],
activeCounter = 0,
xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
xMin = xExtremes.min,
xMax = xExtremes.max,
validValue,
withinRange,
dataMin,
dataMax,
x,
y,
i,
j;
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// For points within the visible range, including the first point outside the
// visible range, consider y extremes
validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
(xData[i - 1] || x) <= xMax);
if (validValue && withinRange) {
j = y.length;
if (j) { // array, like ohlc or range data
while (j--) {
if (y[j] !== null) {
activeYData[activeCounter++] = y[j];
}
}
} else {
activeYData[activeCounter++] = y;
}
}
}
this.dataMin = pick(dataMin, arrayMin(activeYData));
this.dataMax = pick(dataMax, arrayMax(activeYData));
},
/**
* Translate data points from raw data values to chart specific positioning data
* needed later in drawPoints, drawGraph and drawTracker.
*/
translate: function () {
if (!this.processedXData) { // hidden series
this.processData();
}
this.generatePoints();
var series = this,
options = series.options,
stacking = options.stacking,
xAxis = series.xAxis,
categories = xAxis.categories,
yAxis = series.yAxis,
points = series.points,
dataLength = points.length,
hasModifyValue = !!series.modifyValue,
i,
pointPlacement = options.pointPlacement,
dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
threshold = options.threshold;
// Translate each point
for (i = 0; i < dataLength; i++) {
var point = points[i],
xValue = point.x,
yValue = point.y,
yBottom = point.low,
stack = yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
pointStack,
stackValues;
// Discard disallowed y values for log axes
if (yAxis.isLog && yValue <= 0) {
point.y = yValue = null;
}
// Get the plotX translation
point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
// Calculate the bottom y value for stacked series
if (stacking && series.visible && stack && stack[xValue]) {
pointStack = stack[xValue];
stackValues = pointStack.points[series.index];
yBottom = stackValues[0];
yValue = stackValues[1];
if (yBottom === 0) {
yBottom = pick(threshold, yAxis.min);
}
if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
yBottom = null;
}
point.total = point.stackTotal = pointStack.total;
point.percentage = stacking === 'percent' && (point.y / pointStack.total * 100);
point.stackY = yValue;
// Place the stack label
pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
}
// Set translated yBottom or remove it
point.yBottom = defined(yBottom) ?
yAxis.translate(yBottom, 0, 1, 0, 1) :
null;
// general hook, used for Highstock compare mode
if (hasModifyValue) {
yValue = series.modifyValue(yValue, point);
}
// Set the the plotY value, reset it for redraws
point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
//mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591
yAxis.translate(yValue, 0, 1, 0, 1) :
UNDEFINED;
// Set client related positions for mouse tracking
point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514
point.negative = point.y < (threshold || 0);
// some API data
point.category = categories && categories[point.x] !== UNDEFINED ?
categories[point.x] : point.x;
}
// now that we have the cropped data, build the segments
series.getSegments();
},
/**
* Memoize tooltip texts and positions
*/
setTooltipPoints: function (renew) {
var series = this,
points = [],
pointsLength,
low,
high,
xAxis = series.xAxis,
xExtremes = xAxis && xAxis.getExtremes(),
axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar
point,
pointX,
nextPoint,
i,
tooltipPoints = []; // a lookup array for each pixel in the x dimension
// don't waste resources if tracker is disabled
if (series.options.enableMouseTracking === false) {
return;
}
// renew
if (renew) {
series.tooltipPoints = null;
}
// concat segments to overcome null values
each(series.segments || series.points, function (segment) {
points = points.concat(segment);
});
// Reverse the points in case the X axis is reversed
if (xAxis && xAxis.reversed) {
points = points.reverse();
}
// Polar needs additional shaping
if (series.orderTooltipPoints) {
series.orderTooltipPoints(points);
}
// Assign each pixel position to the nearest point
pointsLength = points.length;
for (i = 0; i < pointsLength; i++) {
point = points[i];
pointX = point.x;
if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149
nextPoint = points[i + 1];
// Set this range's low to the last range's high plus one
low = high === UNDEFINED ? 0 : high + 1;
// Now find the new high
high = points[i + 1] ?
mathMin(mathMax(0, mathFloor( // #2070
(point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2
)), axisLength) :
axisLength;
while (low >= 0 && low <= high) {
tooltipPoints[low++] = point;
}
}
}
series.tooltipPoints = tooltipPoints;
},
/**
* Format the header of the tooltip
*/
tooltipHeaderFormatter: function (point) {
var series = this,
tooltipOptions = series.tooltipOptions,
xDateFormat = tooltipOptions.xDateFormat,
dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats,
xAxis = series.xAxis,
isDateTime = xAxis && xAxis.options.type === 'datetime',
headerFormat = tooltipOptions.headerFormat,
closestPointRange = xAxis && xAxis.closestPointRange,
n;
// Guess the best date format based on the closest point distance (#568)
if (isDateTime && !xDateFormat) {
if (closestPointRange) {
for (n in timeUnits) {
if (timeUnits[n] >= closestPointRange) {
xDateFormat = dateTimeLabelFormats[n];
break;
}
}
} else {
xDateFormat = dateTimeLabelFormats.day;
}
}
// Insert the header date format if any
if (isDateTime && xDateFormat && isNumber(point.key)) {
headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}');
}
return format(headerFormat, {
point: point,
series: series
});
},
/**
* Series mouse over handler
*/
onMouseOver: function () {
var series = this,
chart = series.chart,
hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState(HOVER_STATE);
chart.hoverSeries = series;
},
/**
* Series mouse out handler
*/
onMouseOut: function () {
// trigger the event only if listeners exist
var series = this,
options = series.options,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// set normal state
series.setState();
chart.hoverSeries = null;
},
/**
* Animate in the series
*/
animate: function (init) {
var series = this,
chart = series.chart,
renderer = chart.renderer,
clipRect,
markerClipRect,
animation = series.options.animation,
clipBox = chart.clipBox,
inverted = chart.inverted,
sharedClipKey;
// Animation option is set to true
if (animation && !isObject(animation)) {
animation = defaultPlotOptions[series.type].animation;
}
sharedClipKey = '_sharedClip' + animation.duration + animation.easing;
// Initialize the animation. Set up the clipping rectangle.
if (init) {
// If a clipping rectangle with the same properties is currently present in the chart, use that.
clipRect = chart[sharedClipKey];
markerClipRect = chart[sharedClipKey + 'm'];
if (!clipRect) {
chart[sharedClipKey] = clipRect = renderer.clipRect(
extend(clipBox, { width: 0 })
);
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
series.group.clip(clipRect);
series.markerGroup.clip(markerClipRect);
series.sharedClipKey = sharedClipKey;
// Run the animation
} else {
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
// which should be available to the user).
series.animationTimeout = setTimeout(function () {
series.afterAnimate();
}, animation.duration);
}
},
/**
* This runs after animation to land on the final plot clipping
*/
afterAnimate: function () {
var chart = this.chart,
sharedClipKey = this.sharedClipKey,
group = this.group;
if (group && this.options.clip !== false) {
group.clip(chart.clipRect);
this.markerGroup.clip(); // no clip
}
// Remove the shared clipping rectancgle when all series are shown
setTimeout(function () {
if (sharedClipKey && chart[sharedClipKey]) {
chart[sharedClipKey] = chart[sharedClipKey].destroy();
chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
}
}, 100);
},
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
pointAttr,
points = series.points,
chart = series.chart,
plotX,
plotY,
i,
point,
radius,
symbol,
isImage,
graphic,
options = series.options,
seriesMarkerOptions = options.marker,
pointMarkerOptions,
enabled,
isInside,
markerGroup = series.markerGroup;
if (seriesMarkerOptions.enabled || series._hasPointMarkers) {
i = points.length;
while (i--) {
point = points[i];
plotX = mathFloor(point.plotX); // #1843
plotY = point.plotY;
graphic = point.graphic;
pointMarkerOptions = point.marker || {};
enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858
// only draw the point if y is defined
if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
// shortcuts
pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE];
radius = pointAttr.r;
symbol = pick(pointMarkerOptions.symbol, series.symbol);
isImage = symbol.indexOf('url') === 0;
if (graphic) { // update
graphic
.attr({ // Since the marker group isn't clipped, each individual marker must be toggled
visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN
})
.animate(extend({
x: plotX - radius,
y: plotY - radius
}, graphic.symbolName ? { // don't apply to image symbols #507
width: 2 * radius,
height: 2 * radius
} : {}));
} else if (isInside && (radius > 0 || isImage)) {
point.graphic = graphic = chart.renderer.symbol(
symbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius
)
.attr(pointAttr)
.add(markerGroup);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
}
}
},
/**
* Convert state properties from API naming conventions to SVG attributes
*
* @param {Object} options API options object
* @param {Object} base1 SVG attribute object to inherit from
* @param {Object} base2 Second level SVG attribute object to inherit from
*/
convertAttribs: function (options, base1, base2, base3) {
var conversion = this.pointAttrToOptions,
attr,
option,
obj = {};
options = options || {};
base1 = base1 || {};
base2 = base2 || {};
base3 = base3 || {};
for (attr in conversion) {
option = conversion[attr];
obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
}
return obj;
},
/**
* Get the state attributes. Each series type has its own set of attributes
* that are allowed to change on a point's state change. Series wide attributes are stored for
* all series, and additionally point specific attributes are stored for all
* points with individual marker options. If such options are not defined for the point,
* a reference to the series wide attributes is stored in point.pointAttr.
*/
getAttribs: function () {
var series = this,
seriesOptions = series.options,
normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
stateOptions = normalOptions.states,
stateOptionsHover = stateOptions[HOVER_STATE],
pointStateOptionsHover,
seriesColor = series.color,
normalDefaults = {
stroke: seriesColor,
fill: seriesColor
},
points = series.points || [], // #927
i,
point,
seriesPointAttr = [],
pointAttr,
pointAttrToOptions = series.pointAttrToOptions,
hasPointSpecificOptions,
negativeColor = seriesOptions.negativeColor,
defaultLineColor = normalOptions.lineColor,
key;
// series type specific modifications
if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
// if no hover radius is given, default to normal radius + 2
stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2;
stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1;
} else { // column, bar, pie
// if no hover color is given, brighten the normal color
stateOptionsHover.color = stateOptionsHover.color ||
Color(stateOptionsHover.color || seriesColor)
.brighten(stateOptionsHover.brightness).get();
}
// general point attributes for the series normal state
seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
// HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
each([HOVER_STATE, SELECT_STATE], function (state) {
seriesPointAttr[state] =
series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
});
// set it
series.pointAttr = seriesPointAttr;
// Generate the point-specific attribute collections if specific point
// options are given. If not, create a referance to the series wide point
// attributes
i = points.length;
while (i--) {
point = points[i];
normalOptions = (point.options && point.options.marker) || point.options;
if (normalOptions && normalOptions.enabled === false) {
normalOptions.radius = 0;
}
if (point.negative && negativeColor) {
point.color = point.fillColor = negativeColor;
}
hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
// check if the point has specific visual options
if (point.options) {
for (key in pointAttrToOptions) {
if (defined(normalOptions[pointAttrToOptions[key]])) {
hasPointSpecificOptions = true;
}
}
}
// a specific marker config object is defined for the individual point:
// create it's own attribute collection
if (hasPointSpecificOptions) {
normalOptions = normalOptions || {};
pointAttr = [];
stateOptions = normalOptions.states || {}; // reassign for individual point
pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
// Handle colors for column and pies
if (!seriesOptions.marker) { // column, bar, point
// if no hover color is given, brighten the normal color
pointStateOptionsHover.color =
Color(pointStateOptionsHover.color || point.color)
.brighten(pointStateOptionsHover.brightness ||
stateOptionsHover.brightness).get();
}
// normal point state inherits series wide normal state
pointAttr[NORMAL_STATE] = series.convertAttribs(extend({
color: point.color, // #868
fillColor: point.color, // Individual point color or negative color markers (#2219)
lineColor: defaultLineColor === null ? point.color : UNDEFINED // Bubbles take point color, line markers use white
}, normalOptions), seriesPointAttr[NORMAL_STATE]);
// inherit from point normal and series hover
pointAttr[HOVER_STATE] = series.convertAttribs(
stateOptions[HOVER_STATE],
seriesPointAttr[HOVER_STATE],
pointAttr[NORMAL_STATE]
);
// inherit from point normal and series hover
pointAttr[SELECT_STATE] = series.convertAttribs(
stateOptions[SELECT_STATE],
seriesPointAttr[SELECT_STATE],
pointAttr[NORMAL_STATE]
);
// no marker config object is created: copy a reference to the series-wide
// attribute collection
} else {
pointAttr = seriesPointAttr;
}
point.pointAttr = pointAttr;
}
},
/**
* Update the series with a new set of options
*/
update: function (newOptions, redraw) {
var chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
proto = seriesTypes[oldType].prototype,
n;
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, { data: this.options.data }, newOptions);
// Destroy the series and reinsert methods from the type prototype
this.remove(false);
for (n in proto) { // Overwrite series-type specific methods (#2270)
if (proto.hasOwnProperty(n)) {
this[n] = UNDEFINED;
}
}
extend(this, seriesTypes[newOptions.type || oldType].prototype);
this.init(chart, newOptions);
if (pick(redraw, true)) {
chart.redraw(false);
}
},
/**
* Clear DOM objects and free up memory
*/
destroy: function () {
var series = this,
chart = series.chart,
issue134 = /AppleWebKit\/533/.test(userAgent),
destroy,
i,
data = series.data || [],
point,
prop,
axis;
// add event hook
fireEvent(series, 'destroy');
// remove all events
removeEvent(series);
// erase from axes
each(['xAxis', 'yAxis'], function (AXIS) {
axis = series[AXIS];
if (axis) {
erase(axis.series, series);
axis.isDirty = axis.forceRedraw = true;
axis.stacks = {}; // Rebuild stacks when updating (#2229)
}
});
// remove legend items
if (series.legendItem) {
series.chart.legend.destroyItem(series);
}
// destroy all points with their elements
i = data.length;
while (i--) {
point = data[i];
if (point && point.destroy) {
point.destroy();
}
}
series.points = null;
// Clear the animation timeout if we are destroying the series during initial animation
clearTimeout(series.animationTimeout);
// destroy all SVGElements associated to the series
each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
if (series[prop]) {
// issue 134 workaround
destroy = issue134 && prop === 'group' ?
'hide' :
'destroy';
series[prop][destroy]();
}
});
// remove from hoverSeries
if (chart.hoverSeries === series) {
chart.hoverSeries = null;
}
erase(chart.series, series);
// clear all members
for (prop in series) {
delete series[prop];
}
},
/**
* Draw the data labels
*/
drawDataLabels: function () {
var series = this,
seriesOptions = series.options,
cursor = seriesOptions.cursor,
options = seriesOptions.dataLabels,
points = series.points,
pointOptions,
generalOptions,
str,
dataLabelsGroup;
if (options.enabled || series._hasPointLabels) {
// Process default alignment of data labels for columns
if (series.dlProcessOptions) {
series.dlProcessOptions(options);
}
// Create a separate group for the data labels to avoid rotation
dataLabelsGroup = series.plotGroup(
'dataLabelsGroup',
'data-labels',
series.visible ? VISIBLE : HIDDEN,
options.zIndex || 6
);
// Make the labels for each point
generalOptions = options;
each(points, function (point) {
var enabled,
dataLabel = point.dataLabel,
labelConfig,
attr,
name,
rotation,
connector = point.connector,
isNew = true;
// Determine if each data label is enabled
pointOptions = point.options && point.options.dataLabels;
enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
// If the point is outside the plot area, destroy it. #678, #820
if (dataLabel && !enabled) {
point.dataLabel = dataLabel.destroy();
// Individual labels are disabled if the are explicitly disabled
// in the point options, or if they fall outside the plot area.
} else if (enabled) {
// Create individual options structure that can be extended without
// affecting others
options = merge(generalOptions, pointOptions);
rotation = options.rotation;
// Get the string
labelConfig = point.getLabelConfig();
str = options.format ?
format(options.format, labelConfig) :
options.formatter.call(labelConfig, options);
// Determine the color
options.style.color = pick(options.color, options.style.color, series.color, 'black');
// update existing label
if (dataLabel) {
if (defined(str)) {
dataLabel
.attr({
text: str
});
isNew = false;
} else { // #1437 - the label is shown conditionally
point.dataLabel = dataLabel = dataLabel.destroy();
if (connector) {
point.connector = connector.destroy();
}
}
// create new label
} else if (defined(str)) {
attr = {
//align: align,
fill: options.backgroundColor,
stroke: options.borderColor,
'stroke-width': options.borderWidth,
r: options.borderRadius || 0,
rotation: rotation,
padding: options.padding,
zIndex: 1
};
// Remove unused attributes (#947)
for (name in attr) {
if (attr[name] === UNDEFINED) {
delete attr[name];
}
}
dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation
str,
0,
-999,
null,
null,
null,
options.useHTML
)
.attr(attr)
.css(extend(options.style, cursor && { cursor: cursor }))
.add(dataLabelsGroup)
.shadow(options.shadow);
}
if (dataLabel) {
// Now the data label is created and placed at 0,0, so we need to align it
series.alignDataLabel(point, dataLabel, options, null, isNew);
}
}
});
}
},
/**
* Align each individual data label
*/
alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
plotX = pick(point.plotX, -999),
plotY = pick(point.plotY, -999),
bBox = dataLabel.getBBox(),
visible = this.visible && chart.isInsidePlot(point.plotX, point.plotY, inverted),
alignAttr; // the final position;
if (visible) {
// The alignment box is a singular point
alignTo = extend({
x: inverted ? chart.plotWidth - plotY : plotX,
y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
width: 0,
height: 0
}, alignTo);
// Add the text size for alignment calculation
extend(options, {
width: bBox.width,
height: bBox.height
});
// Allow a hook for changing alignment in the last moment, then do the alignment
if (options.rotation) { // Fancy box alignment isn't supported for rotated text
alignAttr = {
align: options.align,
x: alignTo.x + options.x + alignTo.width / 2,
y: alignTo.y + options.y + alignTo.height / 2
};
dataLabel[isNew ? 'attr' : 'animate'](alignAttr);
} else {
dataLabel.align(options, null, alignTo);
alignAttr = dataLabel.alignAttr;
// Handle justify or crop
if (pick(options.overflow, 'justify') === 'justify') {
this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
} else if (pick(options.crop, true)) {
// Now check that the data label is within the plot area
visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
}
}
}
// Show or hide based on the final aligned position
if (!visible) {
dataLabel.attr({ y: -999 });
}
},
/**
* If data labels fall partly outside the plot area, align them back in, in a way that
* doesn't hide the point.
*/
justifyDataLabel: function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
var chart = this.chart,
align = options.align,
verticalAlign = options.verticalAlign,
off,
justified;
// Off left
off = alignAttr.x;
if (off < 0) {
if (align === 'right') {
options.align = 'left';
} else {
options.x = -off;
}
justified = true;
}
// Off right
off = alignAttr.x + bBox.width;
if (off > chart.plotWidth) {
if (align === 'left') {
options.align = 'right';
} else {
options.x = chart.plotWidth - off;
}
justified = true;
}
// Off top
off = alignAttr.y;
if (off < 0) {
if (verticalAlign === 'bottom') {
options.verticalAlign = 'top';
} else {
options.y = -off;
}
justified = true;
}
// Off bottom
off = alignAttr.y + bBox.height;
if (off > chart.plotHeight) {
if (verticalAlign === 'top') {
options.verticalAlign = 'bottom';
} else {
options.y = chart.plotHeight - off;
}
justified = true;
}
if (justified) {
dataLabel.placed = !isNew;
dataLabel.align(options, null, alignTo);
}
},
/**
* Return the graph path of a segment
*/
getSegmentPath: function (segment) {
var series = this,
segmentPath = [],
step = series.options.step;
// build the segment line
each(segment, function (point, i) {
var plotX = point.plotX,
plotY = point.plotY,
lastPoint;
if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
} else {
// moveTo or lineTo
segmentPath.push(i ? L : M);
// step line?
if (step && i) {
lastPoint = segment[i - 1];
if (step === 'right') {
segmentPath.push(
lastPoint.plotX,
plotY
);
} else if (step === 'center') {
segmentPath.push(
(lastPoint.plotX + plotX) / 2,
lastPoint.plotY,
(lastPoint.plotX + plotX) / 2,
plotY
);
} else {
segmentPath.push(
plotX,
lastPoint.plotY
);
}
}
// normal line to next point
segmentPath.push(
point.plotX,
point.plotY
);
}
});
return segmentPath;
},
/**
* Get the graph path
*/
getGraphPath: function () {
var series = this,
graphPath = [],
segmentPath,
singlePoints = []; // used in drawTracker
// Divide into segments and build graph and area paths
each(series.segments, function (segment) {
segmentPath = series.getSegmentPath(segment);
// add the segment to the graph, or a single point for tracking
if (segment.length > 1) {
graphPath = graphPath.concat(segmentPath);
} else {
singlePoints.push(segment[0]);
}
});
// Record it for use in drawGraph and drawTracker, and return graphPath
series.singlePoints = singlePoints;
series.graphPath = graphPath;
return graphPath;
},
/**
* Draw the actual graph
*/
drawGraph: function () {
var series = this,
options = this.options,
props = [['graph', options.lineColor || this.color]],
lineWidth = options.lineWidth,
dashStyle = options.dashStyle,
roundCap = options.linecap !== 'square',
graphPath = this.getGraphPath(),
negativeColor = options.negativeColor;
if (negativeColor) {
props.push(['graphNeg', negativeColor]);
}
// draw the graph
each(props, function (prop, i) {
var graphKey = prop[0],
graph = series[graphKey],
attribs;
if (graph) {
stop(graph); // cancel running animations, #459
graph.animate({ d: graphPath });
} else if (lineWidth && graphPath.length) { // #1487
attribs = {
stroke: prop[1],
'stroke-width': lineWidth,
zIndex: 1 // #1069
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
} else if (roundCap) {
attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
}
series[graphKey] = series.chart.renderer.path(graphPath)
.attr(attribs)
.add(series.group)
.shadow(!i && options.shadow);
}
});
},
/**
* Clip the graphs into the positive and negative coloured graphs
*/
clipNeg: function () {
var options = this.options,
chart = this.chart,
renderer = chart.renderer,
negativeColor = options.negativeColor || options.negativeFillColor,
translatedThreshold,
posAttr,
negAttr,
graph = this.graph,
area = this.area,
posClip = this.posClip,
negClip = this.negClip,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartSizeMax = mathMax(chartWidth, chartHeight),
yAxis = this.yAxis,
above,
below;
if (negativeColor && (graph || area)) {
translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true));
above = {
x: 0,
y: 0,
width: chartSizeMax,
height: translatedThreshold
};
below = {
x: 0,
y: translatedThreshold,
width: chartSizeMax,
height: chartSizeMax
};
if (chart.inverted) {
above.height = below.y = chart.plotWidth - translatedThreshold;
if (renderer.isVML) {
above = {
x: chart.plotWidth - translatedThreshold - chart.plotLeft,
y: 0,
width: chartWidth,
height: chartHeight
};
below = {
x: translatedThreshold + chart.plotLeft - chartWidth,
y: 0,
width: chart.plotLeft + translatedThreshold,
height: chartWidth
};
}
}
if (yAxis.reversed) {
posAttr = below;
negAttr = above;
} else {
posAttr = above;
negAttr = below;
}
if (posClip) { // update
posClip.animate(posAttr);
negClip.animate(negAttr);
} else {
this.posClip = posClip = renderer.clipRect(posAttr);
this.negClip = negClip = renderer.clipRect(negAttr);
if (graph && this.graphNeg) {
graph.clip(posClip);
this.graphNeg.clip(negClip);
}
if (area) {
area.clip(posClip);
this.areaNeg.clip(negClip);
}
}
}
},
/**
* Initialize and perform group inversion on series.group and series.markerGroup
*/
invertGroups: function () {
var series = this,
chart = series.chart;
// Pie, go away (#1736)
if (!series.xAxis) {
return;
}
// A fixed size is needed for inversion to work
function setInvert() {
var size = {
width: series.yAxis.len,
height: series.xAxis.len
};
each(['group', 'markerGroup'], function (groupName) {
if (series[groupName]) {
series[groupName].attr(size).invert();
}
});
}
addEvent(chart, 'resize', setInvert); // do it on resize
addEvent(series, 'destroy', function () {
removeEvent(chart, 'resize', setInvert);
});
// Do it now
setInvert(); // do it now
// On subsequent render and redraw, just do setInvert without setting up events again
series.invertGroups = setInvert;
},
/**
* General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
* series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
*/
plotGroup: function (prop, name, visibility, zIndex, parent) {
var group = this[prop],
isNew = !group;
// Generate it on first call
if (isNew) {
this[prop] = group = this.chart.renderer.g(name)
.attr({
visibility: visibility,
zIndex: zIndex || 0.1 // IE8 needs this
})
.add(parent);
}
// Place it on first and subsequent (redraw) calls
group[isNew ? 'attr' : 'animate'](this.getPlotBox());
return group;
},
/**
* Get the translation and scale for the plot area of this series
*/
getPlotBox: function () {
return {
translateX: this.xAxis ? this.xAxis.left : this.chart.plotLeft,
translateY: this.yAxis ? this.yAxis.top : this.chart.plotTop,
scaleX: 1, // #1623
scaleY: 1
};
},
/**
* Render the graph and markers
*/
render: function () {
var series = this,
chart = series.chart,
group,
options = series.options,
animation = options.animation,
doAnimation = animation && !!series.animate &&
chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden,
// and looks bad in other oldIE
visibility = series.visible ? VISIBLE : HIDDEN,
zIndex = options.zIndex,
hasRendered = series.hasRendered,
chartSeriesGroup = chart.seriesGroup;
// the group
group = series.plotGroup(
'group',
'series',
visibility,
zIndex,
chartSeriesGroup
);
series.markerGroup = series.plotGroup(
'markerGroup',
'markers',
visibility,
zIndex,
chartSeriesGroup
);
// initiate the animation
if (doAnimation) {
series.animate(true);
}
// cache attributes for shapes
series.getAttribs();
// SVGRenderer needs to know this before drawing elements (#1089, #1795)
group.inverted = series.isCartesian ? chart.inverted : false;
// draw the graph if any
if (series.drawGraph) {
series.drawGraph();
series.clipNeg();
}
// draw the data labels (inn pies they go before the points)
series.drawDataLabels();
// draw the points
series.drawPoints();
// draw the mouse tracking area
if (series.options.enableMouseTracking !== false) {
series.drawTracker();
}
// Handle inverted series and tracker groups
if (chart.inverted) {
series.invertGroups();
}
// Initial clipping, must be defined after inverting groups for VML
if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
group.clip(chart.clipRect);
}
// Run the animation
if (doAnimation) {
series.animate();
} else if (!hasRendered) {
series.afterAnimate();
}
series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
series.hasRendered = true;
},
/**
* Redraw the series after an update in the axes.
*/
redraw: function () {
var series = this,
chart = series.chart,
wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
series.setTooltipPoints(true);
series.render();
if (wasDirtyData) {
fireEvent(series, 'updatedData');
}
},
/**
* Set the state of the graph
*/
setState: function (state) {
var series = this,
options = series.options,
graph = series.graph,
graphNeg = series.graphNeg,
stateOptions = options.states,
lineWidth = options.lineWidth,
attribs;
state = state || NORMAL_STATE;
if (series.state !== state) {
series.state = state;
if (stateOptions[state] && stateOptions[state].enabled === false) {
return;
}
if (state) {
lineWidth = stateOptions[state].lineWidth || lineWidth + 1;
}
if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
attribs = {
'stroke-width': lineWidth
};
// use attr because animate will cause any other animation on the graph to stop
graph.attr(attribs);
if (graphNeg) {
graphNeg.attr(attribs);
}
}
}
},
/**
* Set the visibility of the graph
*
* @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
* the visibility is toggled.
*/
setVisible: function (vis, redraw) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
each(chart.series, function (otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
each(series.linkedSeries, function (otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
fireEvent(series, showOrHide);
},
/**
* Show the graph
*/
show: function () {
this.setVisible(true);
},
/**
* Hide the graph
*/
hide: function () {
this.setVisible(false);
},
/**
* Set the selected state of the graph
*
* @param selected {Boolean} True to select the series, false to unselect. If
* UNDEFINED, the selection state is toggled.
*/
select: function (selected) {
var series = this;
// if called without an argument, toggle
series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*/
drawTracker: function () {
var series = this,
options = series.options,
trackByArea = options.trackByArea,
trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
trackerPathLength = trackerPath.length,
chart = series.chart,
pointer = chart.pointer,
renderer = chart.renderer,
snap = chart.options.tooltip.snap,
tracker = series.tracker,
cursor = options.cursor,
css = cursor && { cursor: cursor },
singlePoints = series.singlePoints,
singlePoint,
i,
onMouseOver = function () {
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
};
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === M) { // extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
}
if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// handle single points
for (i = 0; i < singlePoints.length; i++) {
singlePoint = singlePoints[i];
trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
L, singlePoint.plotX + snap, singlePoint.plotY);
}
// draw the tracker
if (tracker) {
tracker.attr({ d: trackerPath });
} else { // create
series.tracker = renderer.path(trackerPath)
.attr({
'stroke-linejoin': 'round', // #1225
visibility: series.visible ? VISIBLE : HIDDEN,
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : NONE,
'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
zIndex: 2
})
.add(series.group);
// The tracker is added to the series group, which is clipped, but is covered
// by the marker group. So the marker group also needs to capture events.
each([series.tracker, series.markerGroup], function (tracker) {
tracker.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
}
}; // end Series prototype
/**
* LineSeries object
*/
var LineSeries = extendClass(Series);
seriesTypes.line = LineSeries;
/**
* Set the default options for area
*/
defaultPlotOptions.area = merge(defaultSeriesOptions, {
threshold: 0
// trackByArea: false,
// lineColor: null, // overrides color, but lets fillColor be unaltered
// fillOpacity: 0.75,
// fillColor: null
});
/**
* AreaSeries object
*/
var AreaSeries = extendClass(Series, {
type: 'area',
/**
* For stacks, don't split segments on null values. Instead, draw null values with
* no marker. Also insert dummy points for any X position that exists in other series
* in the stack.
*/
getSegments: function () {
var segments = [],
segment = [],
keys = [],
xAxis = this.xAxis,
yAxis = this.yAxis,
stack = yAxis.stacks[this.stackKey],
pointMap = {},
plotX,
plotY,
points = this.points,
connectNulls = this.options.connectNulls,
val,
i,
x;
if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
// Create a map where we can quickly look up the points by their X value.
for (i = 0; i < points.length; i++) {
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
for (x in stack) {
if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
keys.push(+x);
}
}
keys.sort(function (a, b) {
return a - b;
});
each(keys, function (x) {
if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
return;
// The point exists, push it to the segment
} else if (pointMap[x]) {
segment.push(pointMap[x]);
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
} else {
plotX = xAxis.translate(x);
val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991
plotY = yAxis.toPixels(val, true);
segment.push({
y: null,
plotX: plotX,
clientX: plotX,
plotY: plotY,
yBottom: plotY,
onMouseOver: noop
});
}
});
if (segment.length) {
segments.push(segment);
}
} else {
Series.prototype.getSegments.call(this);
segments = this.segments;
}
this.segments = segments;
},
/**
* Extend the base Series getSegmentPath method by adding the path for the area.
* This path is pushed to the series.areaPath property.
*/
getSegmentPath: function (segment) {
var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
i,
options = this.options,
segLength = segmentPath.length,
translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
yBottom;
if (segLength === 3) { // for animation from 1 to two points
areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
}
if (options.stacking && !this.closedStacks) {
// Follow stack back. Todo: implement areaspline. A general solution could be to
// reverse the entire graphPath of the previous series, though may be hard with
// splines and with series with different extremes
for (i = segment.length - 1; i >= 0; i--) {
yBottom = pick(segment[i].yBottom, translatedThreshold);
// step line?
if (i < segment.length - 1 && options.step) {
areaSegmentPath.push(segment[i + 1].plotX, yBottom);
}
areaSegmentPath.push(segment[i].plotX, yBottom);
}
} else { // follow zero line back
this.closeSegment(areaSegmentPath, segment, translatedThreshold);
}
this.areaPath = this.areaPath.concat(areaSegmentPath);
return segmentPath;
},
/**
* Extendable method to close the segment path of an area. This is overridden in polar
* charts.
*/
closeSegment: function (path, segment, translatedThreshold) {
path.push(
L,
segment[segment.length - 1].plotX,
translatedThreshold,
L,
segment[0].plotX,
translatedThreshold
);
},
/**
* Draw the graph and the underlying area. This method calls the Series base
* function and adds the area. The areaPath is calculated in the getSegmentPath
* method called from Series.prototype.drawGraph.
*/
drawGraph: function () {
// Define or reset areaPath
this.areaPath = [];
// Call the base method
Series.prototype.drawGraph.apply(this);
// Define local variables
var series = this,
areaPath = this.areaPath,
options = this.options,
negativeColor = options.negativeColor,
negativeFillColor = options.negativeFillColor,
props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
if (negativeColor || negativeFillColor) {
props.push(['areaNeg', negativeColor, negativeFillColor]);
}
each(props, function (prop) {
var areaKey = prop[0],
area = series[areaKey];
// Create or update the area
if (area) { // update
area.animate({ d: areaPath });
} else { // create
series[areaKey] = series.chart.renderer.path(areaPath)
.attr({
fill: pick(
prop[2],
Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
),
zIndex: 0 // #1069
}).add(series.group);
}
});
},
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawLegendSymbol: function (legend, item) {
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 11,
legend.options.symbolWidth,
12,
2
).attr({
zIndex: 3
}).add(item.legendGroup);
}
});
seriesTypes.area = AreaSeries;/**
* Set the default options for spline
*/
defaultPlotOptions.spline = merge(defaultSeriesOptions);
/**
* SplineSeries object
*/
var SplineSeries = extendClass(Series, {
type: 'spline',
/**
* Get the spline segment from a given point's previous neighbour to the given point
*/
getPointSpline: function (segment, point, i) {
var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
denom = smoothing + 1,
plotX = point.plotX,
plotY = point.plotY,
lastPoint = segment[i - 1],
nextPoint = segment[i + 1],
leftContX,
leftContY,
rightContX,
rightContY,
ret;
// find control points
if (lastPoint && nextPoint) {
var lastX = lastPoint.plotX,
lastY = lastPoint.plotY,
nextX = nextPoint.plotX,
nextY = nextPoint.plotY,
correction;
leftContX = (smoothing * plotX + lastX) / denom;
leftContY = (smoothing * plotY + lastY) / denom;
rightContX = (smoothing * plotX + nextX) / denom;
rightContY = (smoothing * plotY + nextY) / denom;
// have the two control points make a straight line through main point
correction = ((rightContY - leftContY) * (rightContX - plotX)) /
(rightContX - leftContX) + plotY - rightContY;
leftContY += correction;
rightContY += correction;
// to prevent false extremes, check that control points are between
// neighbouring points' y values
if (leftContY > lastY && leftContY > plotY) {
leftContY = mathMax(lastY, plotY);
rightContY = 2 * plotY - leftContY; // mirror of left control point
} else if (leftContY < lastY && leftContY < plotY) {
leftContY = mathMin(lastY, plotY);
rightContY = 2 * plotY - leftContY;
}
if (rightContY > nextY && rightContY > plotY) {
rightContY = mathMax(nextY, plotY);
leftContY = 2 * plotY - rightContY;
} else if (rightContY < nextY && rightContY < plotY) {
rightContY = mathMin(nextY, plotY);
leftContY = 2 * plotY - rightContY;
}
// record for drawing in next point
point.rightContX = rightContX;
point.rightContY = rightContY;
}
// Visualize control points for debugging
/*
if (leftContX) {
this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
.attr({
stroke: 'red',
'stroke-width': 1,
fill: 'none'
})
.add();
this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'red',
'stroke-width': 1
})
.add();
this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
.attr({
stroke: 'green',
'stroke-width': 1,
fill: 'none'
})
.add();
this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'green',
'stroke-width': 1
})
.add();
}
*/
// moveTo or lineTo
if (!i) {
ret = [M, plotX, plotY];
} else { // curve from last point to this
ret = [
'C',
lastPoint.rightContX || lastPoint.plotX,
lastPoint.rightContY || lastPoint.plotY,
leftContX || plotX,
leftContY || plotY,
plotX,
plotY
];
lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
}
return ret;
}
});
seriesTypes.spline = SplineSeries;
/**
* Set the default options for areaspline
*/
defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
/**
* AreaSplineSeries object
*/
var areaProto = AreaSeries.prototype,
AreaSplineSeries = extendClass(SplineSeries, {
type: 'areaspline',
closedStacks: true, // instead of following the previous graph back, follow the threshold back
// Mix in methods from the area series
getSegmentPath: areaProto.getSegmentPath,
closeSegment: areaProto.closeSegment,
drawGraph: areaProto.drawGraph,
drawLegendSymbol: areaProto.drawLegendSymbol
});
seriesTypes.areaspline = AreaSplineSeries;
/**
* Set the default options for column
*/
defaultPlotOptions.column = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
borderWidth: 1,
borderRadius: 0,
//colorByPoint: undefined,
groupPadding: 0.2,
//grouping: true,
marker: null, // point options are specified in the base options
pointPadding: 0.1,
//pointWidth: null,
minPointLength: 0,
cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
states: {
hover: {
brightness: 0.1,
shadow: false
},
select: {
color: '#C0C0C0',
borderColor: '#000000',
shadow: false
}
},
dataLabels: {
align: null, // auto
verticalAlign: null, // auto
y: null
},
stickyTracking: false,
threshold: 0
});
/**
* ColumnSeries object
*/
var ColumnSeries = extendClass(Series, {
type: 'column',
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
'stroke-width': 'borderWidth',
fill: 'color',
r: 'borderRadius'
},
cropShoulder: 0,
trackerGroups: ['group', 'dataLabelsGroup'],
negStacks: true, // use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
/**
* Initialize the series
*/
init: function () {
Series.prototype.init.apply(this, arguments);
var series = this,
chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
* pointWidth etc.
*/
getColumnMetrics: function () {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
reversedXAxis = xAxis.reversed,
stackKey,
stackGroups = {},
columnIndex,
columnCount = 0;
// Get the total number of column type series.
// This is called on every series. Consider moving this logic to a
// chart.orderStacks() function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
} else {
each(series.chart.series, function (otherSeries) {
var otherOptions = otherSeries.options,
otherYAxis = otherSeries.yAxis;
if (otherSeries.type === series.type && otherSeries.visible &&
yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (stackGroups[stackKey] === UNDEFINED) {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
} else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = mathMin(
mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1),
xAxis.len // #1535
),
groupPadding = categoryWidth * options.groupPadding,
groupWidth = categoryWidth - 2 * groupPadding,
pointOffsetWidth = groupWidth / columnCount,
optionPointWidth = options.pointWidth,
pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
pointOffsetWidth * options.pointPadding,
pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
colIndex = (reversedXAxis ?
columnCount - (series.columnIndex || 0) : // #1251
series.columnIndex) || 0,
pointXOffset = pointPadding + (groupPadding + colIndex *
pointOffsetWidth - (categoryWidth / 2)) *
(reversedXAxis ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
return (series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
});
},
/**
* Translate each point to the plot area coordinate system and find shape positions
*/
translate: function () {
var series = this,
chart = series.chart,
options = series.options,
borderWidth = options.borderWidth,
yAxis = series.yAxis,
threshold = options.threshold,
translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
minPointLength = pick(options.minPointLength, 5),
metrics = series.getColumnMetrics(),
pointWidth = metrics.width,
seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width
pointXOffset = series.pointXOffset = metrics.offset,
xCrisp = -(borderWidth % 2 ? 0.5 : 0),
yCrisp = borderWidth % 2 ? 0.5 : 1;
if (chart.renderer.isVML && chart.inverted) {
yCrisp += 1;
}
Series.prototype.translate.apply(series);
// record the new values
each(series.points, function (point) {
var yBottom = pick(point.yBottom, translatedThreshold),
plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
barX = point.plotX + pointXOffset,
barW = seriesBarW,
barY = mathMin(plotY, yBottom),
right,
bottom,
fromTop,
fromLeft,
barH = mathMax(plotY, yBottom) - barY;
// Handle options.minPointLength
if (mathAbs(barH) < minPointLength) {
if (minPointLength) {
barH = minPointLength;
barY =
mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
yBottom - minPointLength : // keep position
translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
}
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Round off to obtain crisp edges
fromLeft = mathAbs(barX) < 0.5;
right = mathRound(barX + barW) + xCrisp;
barX = mathRound(barX) + xCrisp;
barW = right - barX;
fromTop = mathAbs(barY) < 0.5;
bottom = mathRound(barY + barH) + yCrisp;
barY = mathRound(barY) + yCrisp;
barH = bottom - barY;
// Top and left edges are exceptions
if (fromLeft) {
barX += 1;
barW -= 1;
}
if (fromTop) {
barY -= 1;
barH += 1;
}
// Register shape type and arguments to be used in drawPoints
point.shapeType = 'rect';
point.shapeArgs = {
x: barX,
y: barY,
width: barW,
height: barH
};
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*/
drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
/**
* Columns have no graph
*/
drawGraph: noop,
/**
* Draw the columns. For bars, the series.group is rotated, so the same coordinates
* apply for columns and bars. This method is inherited by scatter series.
*
*/
drawPoints: function () {
var series = this,
options = series.options,
renderer = series.chart.renderer,
shapeArgs;
// draw the columns
each(series.points, function (point) {
var plotY = point.plotY,
graphic = point.graphic;
if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
if (graphic) { // update
stop(graphic);
graphic.animate(merge(shapeArgs));
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE])
.add(series.group)
.shadow(options.shadow, null, options.stacking && !options.borderRadius);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Add tracking event listener to the series group, so the point graphics
* themselves act as trackers
*/
drawTracker: function () {
var series = this,
chart = series.chart,
pointer = chart.pointer,
cursor = series.options.cursor,
css = cursor && { cursor: cursor },
onMouseOver = function (e) {
var target = e.target,
point;
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
while (target && !point) {
point = target.point;
target = target.parentNode;
}
if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
point.onMouseOver(e);
}
};
// Add reference to the point
each(series.points, function (point) {
if (point.graphic) {
point.graphic.element.point = point;
}
if (point.dataLabel) {
point.dataLabel.element.point = point;
}
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
each(series.trackerGroups, function (key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key]
.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
}
});
series._hasTracking = true;
}
},
/**
* Override the basic data label alignment by adjusting for the position of the column
*/
alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)),
inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
// Align to the column itself, or the top of it
if (dlBox) { // Area range uses this method but not alignTo
alignTo = merge(dlBox);
if (inverted) {
alignTo = {
x: chart.plotWidth - alignTo.y - alignTo.height,
y: chart.plotHeight - alignTo.x - alignTo.width,
width: alignTo.height,
height: alignTo.width
};
}
// Compute the alignment box
if (!inside) {
if (inverted) {
alignTo.x += below ? 0 : alignTo.width;
alignTo.width = 0;
} else {
alignTo.y += below ? alignTo.height : 0;
alignTo.height = 0;
}
}
}
// When alignment is undefined (typically columns and bars), display the individual
// point below or above the point depending on the threshold
options.align = pick(
options.align,
!inverted || inside ? 'center' : below ? 'right' : 'left'
);
options.verticalAlign = pick(
options.verticalAlign,
inverted || inside ? 'middle' : below ? 'top' : 'bottom'
);
// Call the parent method
Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
},
/**
* Animate the column heights one by one from zero
* @param {Boolean} init Whether to initialize the animation or run it
*/
animate: function (init) {
var series = this,
yAxis = this.yAxis,
options = series.options,
inverted = this.chart.inverted,
attr = {},
translatedThreshold;
if (hasSVG) { // VML is too slow anyway
if (init) {
attr.scaleY = 0.001;
translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
} else {
attr.translateY = translatedThreshold;
}
series.group.attr(attr);
} else { // run the animation
attr.scaleY = 1;
attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
series.group.animate(attr, series.options.animation);
// delete this function to allow it only once
series.animate = null;
}
}
},
/**
* Remove this series from the chart
*/
remove: function () {
var series = this,
chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
seriesTypes.column = ColumnSeries;
/**
* Set the default options for bar
*/
defaultPlotOptions.bar = merge(defaultPlotOptions.column);
/**
* The Bar series class
*/
var BarSeries = extendClass(ColumnSeries, {
type: 'bar',
inverted: true
});
seriesTypes.bar = BarSeries;
/**
* Set the default options for scatter
*/
defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
lineWidth: 0,
tooltip: {
headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>',
followPointer: true
},
stickyTracking: false
});
/**
* The scatter series class
*/
var ScatterSeries = extendClass(Series, {
type: 'scatter',
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['markerGroup'],
takeOrdinalPosition: false, // #2342
drawTracker: ColumnSeries.prototype.drawTracker,
setTooltipPoints: noop
});
seriesTypes.scatter = ScatterSeries;
/**
* Set the default options for pie
*/
defaultPlotOptions.pie = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
borderWidth: 1,
center: [null, null],
clip: false,
colorByPoint: true, // always true for pies
dataLabels: {
// align: null,
// connectorWidth: 1,
// connectorColor: point.color,
// connectorPadding: 5,
distance: 30,
enabled: true,
formatter: function () {
return this.point.name;
}
// softConnector: true,
//y: 0
},
ignoreHiddenPoint: true,
//innerSize: 0,
legendType: 'point',
marker: null, // point options are specified in the base options
size: null,
showInLegend: false,
slicedOffset: 10,
states: {
hover: {
brightness: 0.1,
shadow: false
}
},
stickyTracking: false,
tooltip: {
followPointer: true
}
});
/**
* Extended point object for pies
*/
var PiePoint = extendClass(Point, {
/**
* Initiate the pie slice
*/
init: function () {
Point.prototype.init.apply(this, arguments);
var point = this,
toggleSlice;
// Disallow negative values (#1530)
if (point.y < 0) {
point.y = null;
}
//visible: options.visible !== false,
extend(point, {
visible: point.visible !== false,
name: pick(point.name, 'Slice')
});
// add event listener for select
toggleSlice = function (e) {
point.slice(e.type === 'select');
};
addEvent(point, 'select', toggleSlice);
addEvent(point, 'unselect', toggleSlice);
return point;
},
/**
* Toggle the visibility of the pie slice
* @param {Boolean} vis Whether to show the slice or not. If undefined, the
* visibility is toggled
*/
setVisible: function (vis) {
var point = this,
series = point.series,
chart = series.chart,
method;
// if called without an argument, toggle visibility
point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
method = vis ? 'show' : 'hide';
// Show and hide associated elements
each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
if (point[key]) {
point[key][method]();
}
});
if (point.legendItem) {
chart.legend.colorizeItem(point, vis);
}
// Handle ignore hidden slices
if (!series.isDirty && series.options.ignoreHiddenPoint) {
series.isDirty = true;
chart.redraw();
}
},
/**
* Set or toggle whether the slice is cut out from the pie
* @param {Boolean} sliced When undefined, the slice state is toggled
* @param {Boolean} redraw Whether to redraw the chart. True by default.
*/
slice: function (sliced, redraw, animation) {
var point = this,
series = point.series,
chart = series.chart,
translation;
setAnimation(animation, chart);
// redraw is true by default
redraw = pick(redraw, true);
// if called without an argument, toggle
point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
translation = sliced ? point.slicedTranslation : {
translateX: 0,
translateY: 0
};
point.graphic.animate(translation);
if (point.shadowGroup) {
point.shadowGroup.animate(translation);
}
}
});
/**
* The Pie series class
*/
var PieSeries = {
type: 'pie',
isCartesian: false,
pointClass: PiePoint,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'dataLabelsGroup'],
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
'stroke-width': 'borderWidth',
fill: 'color'
},
/**
* Pies have one color each point
*/
getColor: noop,
/**
* Animate the pies in
*/
animate: function (init) {
var series = this,
points = series.points,
startAngleRad = series.startAngleRad;
if (!init) {
each(points, function (point) {
var graphic = point.graphic,
args = point.shapeArgs;
if (graphic) {
// start values
graphic.attr({
r: series.center[3] / 2, // animate from inner radius (#779)
start: startAngleRad,
end: startAngleRad
});
// animate
graphic.animate({
r: args.r,
start: args.start,
end: args.end
}, series.options.animation);
}
});
// delete this function to allow it only once
series.animate = null;
}
},
/**
* Extend the basic setData method by running processData and generatePoints immediately,
* in order to access the points from the legend.
*/
setData: function (data, redraw) {
Series.prototype.setData.call(this, data, false);
this.processData();
this.generatePoints();
if (pick(redraw, true)) {
this.chart.redraw();
}
},
/**
* Extend the generatePoints method by adding total and percentage properties to each point
*/
generatePoints: function () {
var i,
total = 0,
points,
len,
point,
ignoreHiddenPoint = this.options.ignoreHiddenPoint;
Series.prototype.generatePoints.call(this);
// Populate local vars
points = this.points;
len = points.length;
// Get the total sum
for (i = 0; i < len; i++) {
point = points[i];
total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
}
this.total = total;
// Set each point's properties
for (i = 0; i < len; i++) {
point = points[i];
point.percentage = total > 0 ? (point.y / total) * 100 : 0;
point.total = total;
}
},
/**
* Get the center of the pie based on the size and center options relative to the
* plot area. Borrowed by the polar and gauge series types.
*/
getCenter: function () {
var options = this.options,
chart = this.chart,
slicingRoom = 2 * (options.slicedOffset || 0),
handleSlicingRoom,
plotWidth = chart.plotWidth - 2 * slicingRoom,
plotHeight = chart.plotHeight - 2 * slicingRoom,
centerOption = options.center,
positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
smallestSize = mathMin(plotWidth, plotHeight),
isPercent;
return map(positions, function (length, i) {
isPercent = /%$/.test(length);
handleSlicingRoom = i < 2 || (i === 2 && isPercent);
return (isPercent ?
// i == 0: centerX, relative to width
// i == 1: centerY, relative to height
// i == 2: size, relative to smallestSize
// i == 4: innerSize, relative to smallestSize
[plotWidth, plotHeight, smallestSize, smallestSize][i] *
pInt(length) / 100 :
length) + (handleSlicingRoom ? slicingRoom : 0);
});
},
/**
* Do translation for pie slices
*/
translate: function (positions) {
this.generatePoints();
var series = this,
cumulative = 0,
precision = 1000, // issue #172
options = series.options,
slicedOffset = options.slicedOffset,
connectorOffset = slicedOffset + options.borderWidth,
start,
end,
angle,
startAngle = options.startAngle || 0,
startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
endAngleRad = series.endAngleRad = mathPI / 180 * ((options.endAngle || (startAngle + 360)) - 90),
circ = endAngleRad - startAngleRad, //2 * mathPI,
points = series.points,
radiusX, // the x component of the radius vector for a given point
radiusY,
labelDistance = options.dataLabels.distance,
ignoreHiddenPoint = options.ignoreHiddenPoint,
i,
len = points.length,
point;
// Get positions - either an integer or a percentage string must be given.
// If positions are passed as a parameter, we're in a recursive loop for adjusting
// space for data labels.
if (!positions) {
series.center = positions = series.getCenter();
}
// utility for getting the x value from a given y, used for anticollision logic in data labels
series.getX = function (y, left) {
angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance));
return positions[0] +
(left ? -1 : 1) *
(mathCos(angle) * (positions[2] / 2 + labelDistance));
};
// Calculate the geometry for each point
for (i = 0; i < len; i++) {
point = points[i];
// set start and end angle
start = startAngleRad + (cumulative * circ);
if (!ignoreHiddenPoint || point.visible) {
cumulative += point.percentage / 100;
}
end = startAngleRad + (cumulative * circ);
// set the shape
point.shapeType = 'arc';
point.shapeArgs = {
x: positions[0],
y: positions[1],
r: positions[2] / 2,
innerR: positions[3] / 2,
start: mathRound(start * precision) / precision,
end: mathRound(end * precision) / precision
};
// center for the sliced out slice
angle = (end + start) / 2;
if (angle > 0.75 * circ) {
angle -= 2 * mathPI;
}
point.slicedTranslation = {
translateX: mathRound(mathCos(angle) * slicedOffset),
translateY: mathRound(mathSin(angle) * slicedOffset)
};
// set the anchor point for tooltips
radiusX = mathCos(angle) * positions[2] / 2;
radiusY = mathSin(angle) * positions[2] / 2;
point.tooltipPos = [
positions[0] + radiusX * 0.7,
positions[1] + radiusY * 0.7
];
point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
point.angle = angle;
// set the anchor point for data labels
connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
point.labelPos = [
positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
positions[0] + radiusX, // landing point for connector
positions[1] + radiusY, // a/a
labelDistance < 0 ? // alignment
'center' :
point.half ? 'right' : 'left', // alignment
angle // center angle
];
}
},
setTooltipPoints: noop,
drawGraph: null,
/**
* Draw the data points
*/
drawPoints: function () {
var series = this,
chart = series.chart,
renderer = chart.renderer,
groupTranslation,
//center,
graphic,
//group,
shadow = series.options.shadow,
shadowGroup,
shapeArgs;
if (shadow && !series.shadowGroup) {
series.shadowGroup = renderer.g('shadow')
.add(series.group);
}
// draw the slices
each(series.points, function (point) {
graphic = point.graphic;
shapeArgs = point.shapeArgs;
shadowGroup = point.shadowGroup;
// put the shadow behind all points
if (shadow && !shadowGroup) {
shadowGroup = point.shadowGroup = renderer.g('shadow')
.add(series.shadowGroup);
}
// if the point is sliced, use special translation, else use plot area traslation
groupTranslation = point.sliced ? point.slicedTranslation : {
translateX: 0,
translateY: 0
};
//group.translate(groupTranslation[0], groupTranslation[1]);
if (shadowGroup) {
shadowGroup.attr(groupTranslation);
}
// draw the slice
if (graphic) {
graphic.animate(extend(shapeArgs, groupTranslation));
} else {
point.graphic = graphic = renderer.arc(shapeArgs)
.setRadialReference(series.center)
.attr(
point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
)
.attr({ 'stroke-linejoin': 'round' })
.attr(groupTranslation)
.add(series.group)
.shadow(shadow, shadowGroup);
}
// detect point specific visibility
if (point.visible === false) {
point.setVisible(false);
}
});
},
/**
* Utility for sorting data labels
*/
sortByAngle: function (points, sign) {
points.sort(function (a, b) {
return a.angle !== undefined && (b.angle - a.angle) * sign;
});
},
/**
* Override the base drawDataLabels method by pie specific functionality
*/
drawDataLabels: function () {
var series = this,
data = series.data,
point,
chart = series.chart,
options = series.options.dataLabels,
connectorPadding = pick(options.connectorPadding, 10),
connectorWidth = pick(options.connectorWidth, 1),
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
connector,
connectorPath,
softConnector = pick(options.softConnector, true),
distanceOption = options.distance,
seriesCenter = series.center,
radius = seriesCenter[2] / 2,
centerY = seriesCenter[1],
outside = distanceOption > 0,
dataLabel,
dataLabelWidth,
labelPos,
labelHeight,
halves = [// divide the points into right and left halves for anti collision
[], // right
[] // left
],
x,
y,
visibility,
rankArr,
i,
j,
overflow = [0, 0, 0, 0], // top, right, bottom, left
sort = function (a, b) {
return b.y - a.y;
};
// get out if not enabled
if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
return;
}
// run parent method
Series.prototype.drawDataLabels.apply(series);
// arrange points for detection collision
each(data, function (point) {
if (point.dataLabel) { // it may have been cancelled in the base method (#407)
halves[point.half].push(point);
}
});
// assume equal label heights
i = 0;
while (!labelHeight && data[i]) { // #1569
labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968
i++;
}
/* Loop over the points in each half, starting from the top and bottom
* of the pie to detect overlapping labels.
*/
i = 2;
while (i--) {
var slots = [],
slotsLength,
usedSlots = [],
points = halves[i],
pos,
length = points.length,
slotIndex;
// Sort by angle
series.sortByAngle(points, i - 0.5);
// Only do anti-collision when we are outside the pie and have connectors (#856)
if (distanceOption > 0) {
// build the slots
for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) {
slots.push(pos);
// visualize the slot
/*
var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
slotY = pos + chart.plotTop;
if (!isNaN(slotX)) {
chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
.attr({
'stroke-width': 1,
stroke: 'silver'
})
.add();
chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4)
.attr({
fill: 'silver'
}).add();
}
*/
}
slotsLength = slots.length;
// if there are more values than available slots, remove lowest values
if (length > slotsLength) {
// create an array for sorting and ranking the points within each quarter
rankArr = [].concat(points);
rankArr.sort(sort);
j = length;
while (j--) {
rankArr[j].rank = j;
}
j = length;
while (j--) {
if (points[j].rank >= slotsLength) {
points.splice(j, 1);
}
}
length = points.length;
}
// The label goes to the nearest open slot, but not closer to the edge than
// the label's index.
for (j = 0; j < length; j++) {
point = points[j];
labelPos = point.labelPos;
var closest = 9999,
distance,
slotI;
// find the closest slot index
for (slotI = 0; slotI < slotsLength; slotI++) {
distance = mathAbs(slots[slotI] - labelPos[1]);
if (distance < closest) {
closest = distance;
slotIndex = slotI;
}
}
// if that slot index is closer to the edges of the slots, move it
// to the closest appropriate slot
if (slotIndex < j && slots[j] !== null) { // cluster at the top
slotIndex = j;
} else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
slotIndex = slotsLength - length + j;
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
} else {
// Slot is taken, find next free slot below. In the next run, the next slice will find the
// slot above these, because it is the closest one
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
}
usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
slots[slotIndex] = null; // mark as taken
}
// sort them in order to fill in from the top
usedSlots.sort(sort);
}
// now the used slots are sorted, fill them up sequentially
for (j = 0; j < length; j++) {
var slot, naturalY;
point = points[j];
labelPos = point.labelPos;
dataLabel = point.dataLabel;
visibility = point.visible === false ? HIDDEN : VISIBLE;
naturalY = labelPos[1];
if (distanceOption > 0) {
slot = usedSlots.pop();
slotIndex = slot.i;
// if the slot next to currrent slot is free, the y value is allowed
// to fall back to the natural position
y = slot.y;
if ((naturalY > y && slots[slotIndex + 1] !== null) ||
(naturalY < y && slots[slotIndex - 1] !== null)) {
y = naturalY;
}
} else {
y = naturalY;
}
// get the x - use the natural x position for first and last slot, to prevent the top
// and botton slice connectors from touching each other on either side
x = options.justify ?
seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i);
// Record the placement and visibility
dataLabel._attr = {
visibility: visibility,
align: labelPos[6]
};
dataLabel._pos = {
x: x + options.x +
({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
y: y + options.y - 10 // 10 is for the baseline (label vs text)
};
dataLabel.connX = x;
dataLabel.connY = y;
// Detect overflowing data labels
if (this.options.size === null) {
dataLabelWidth = dataLabel.width;
// Overflow left
if (x - dataLabelWidth < connectorPadding) {
overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
// Overflow right
} else if (x + dataLabelWidth > plotWidth - connectorPadding) {
overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
}
// Overflow top
if (y - labelHeight / 2 < 0) {
overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
// Overflow left
} else if (y + labelHeight / 2 > plotHeight) {
overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
}
}
} // for each point
} // for each half
// Do not apply the final placement and draw the connectors until we have verified
// that labels are not spilling over.
if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
// Place the labels in the final position
this.placeDataLabels();
// Draw the connectors
if (outside && connectorWidth) {
each(this.points, function (point) {
connector = point.connector;
labelPos = point.labelPos;
dataLabel = point.dataLabel;
if (dataLabel && dataLabel._pos) {
visibility = dataLabel._attr.visibility;
x = dataLabel.connX;
y = dataLabel.connY;
connectorPath = softConnector ? [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'C',
x, y, // first break, next to the label
2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
] : [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
L,
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
];
if (connector) {
connector.animate({ d: connectorPath });
connector.attr('visibility', visibility);
} else {
point.connector = connector = series.chart.renderer.path(connectorPath).attr({
'stroke-width': connectorWidth,
stroke: options.connectorColor || point.color || '#606060',
visibility: visibility
})
.add(series.group);
}
} else if (connector) {
point.connector = connector.destroy();
}
});
}
}
},
/**
* Verify whether the data labels are allowed to draw, or we should run more translation and data
* label positioning to keep them inside the plot area. Returns true when data labels are ready
* to draw.
*/
verifyDataLabelOverflow: function (overflow) {
var center = this.center,
options = this.options,
centerOption = options.center,
minSize = options.minSize || 80,
newSize = minSize,
ret;
// Handle horizontal size and center
if (centerOption[0] !== null) { // Fixed center
newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
} else { // Auto center
newSize = mathMax(
center[2] - overflow[1] - overflow[3], // horizontal overflow
minSize
);
center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
}
// Handle vertical size and center
if (centerOption[1] !== null) { // Fixed center
newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
} else { // Auto center
newSize = mathMax(
mathMin(
newSize,
center[2] - overflow[0] - overflow[2] // vertical overflow
),
minSize
);
center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
}
// If the size must be decreased, we need to run translate and drawDataLabels again
if (newSize < center[2]) {
center[2] = newSize;
this.translate(center);
each(this.points, function (point) {
if (point.dataLabel) {
point.dataLabel._pos = null; // reset
}
});
this.drawDataLabels();
// Else, return true to indicate that the pie and its labels is within the plot area
} else {
ret = true;
}
return ret;
},
/**
* Perform the final placement of the data labels after we have verified that they
* fall within the plot area.
*/
placeDataLabels: function () {
each(this.points, function (point) {
var dataLabel = point.dataLabel,
_pos;
if (dataLabel) {
_pos = dataLabel._pos;
if (_pos) {
dataLabel.attr(dataLabel._attr);
dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
dataLabel.moved = true;
} else if (dataLabel) {
dataLabel.attr({ y: -999 });
}
}
});
},
alignDataLabel: noop,
/**
* Draw point specific tracker objects. Inherit directly from column series.
*/
drawTracker: ColumnSeries.prototype.drawTracker,
/**
* Use a simple symbol from column prototype
*/
drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
/**
* Pies don't have point marker symbols
*/
getSymbol: noop
};
PieSeries = extendClass(Series, PieSeries);
seriesTypes.pie = PieSeries;
/* ****************************************************************************
* Start data grouping module *
******************************************************************************/
/*jslint white:true */
var DATA_GROUPING = 'dataGrouping',
seriesProto = Series.prototype,
baseProcessData = seriesProto.processData,
baseGeneratePoints = seriesProto.generatePoints,
baseDestroy = seriesProto.destroy,
baseTooltipHeaderFormatter = seriesProto.tooltipHeaderFormatter,
NUMBER = 'number',
commonOptions = {
approximation: 'average', // average, open, high, low, close, sum
//enabled: null, // (true for stock charts, false for basic),
//forced: undefined,
groupPixelWidth: 2,
// the first one is the point or start value, the second is the start value if we're dealing with range,
// the third one is the end value if dealing with a range
dateTimeLabelFormats: hash(
MILLISECOND, ['%A, %b %e, %H:%M:%S.%L', '%A, %b %e, %H:%M:%S.%L', '-%H:%M:%S.%L'],
SECOND, ['%A, %b %e, %H:%M:%S', '%A, %b %e, %H:%M:%S', '-%H:%M:%S'],
MINUTE, ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'],
HOUR, ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'],
DAY, ['%A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'],
WEEK, ['Week from %A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'],
MONTH, ['%B %Y', '%B', '-%B %Y'],
YEAR, ['%Y', '%Y', '-%Y']
)
// smoothed = false, // enable this for navigator series only
},
specificOptions = { // extends common options
line: {},
spline: {},
area: {},
areaspline: {},
column: {
approximation: 'sum',
groupPixelWidth: 10
},
arearange: {
approximation: 'range'
},
areasplinerange: {
approximation: 'range'
},
columnrange: {
approximation: 'range',
groupPixelWidth: 10
},
candlestick: {
approximation: 'ohlc',
groupPixelWidth: 10
},
ohlc: {
approximation: 'ohlc',
groupPixelWidth: 5
}
},
// units are defined in a separate array to allow complete overriding in case of a user option
defaultDataGroupingUnits = [[
MILLISECOND, // unit name
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
SECOND,
[1, 2, 5, 10, 15, 30]
], [
MINUTE,
[1, 2, 5, 10, 15, 30]
], [
HOUR,
[1, 2, 3, 4, 6, 8, 12]
], [
DAY,
[1]
], [
WEEK,
[1]
], [
MONTH,
[1, 3, 6]
], [
YEAR,
null
]
],
/**
* Define the available approximation types. The data grouping approximations takes an array
* or numbers as the first parameter. In case of ohlc, four arrays are sent in as four parameters.
* Each array consists only of numbers. In case null values belong to the group, the property
* .hasNulls will be set to true on the array.
*/
approximations = {
sum: function (arr) {
var len = arr.length,
ret;
// 1. it consists of nulls exclusively
if (!len && arr.hasNulls) {
ret = null;
// 2. it has a length and real values
} else if (len) {
ret = 0;
while (len--) {
ret += arr[len];
}
}
// 3. it has zero length, so just return undefined
// => doNothing()
return ret;
},
average: function (arr) {
var len = arr.length,
ret = approximations.sum(arr);
// If we have a number, return it divided by the length. If not, return
// null or undefined based on what the sum method finds.
if (typeof ret === NUMBER && len) {
ret = ret / len;
}
return ret;
},
open: function (arr) {
return arr.length ? arr[0] : (arr.hasNulls ? null : UNDEFINED);
},
high: function (arr) {
return arr.length ? arrayMax(arr) : (arr.hasNulls ? null : UNDEFINED);
},
low: function (arr) {
return arr.length ? arrayMin(arr) : (arr.hasNulls ? null : UNDEFINED);
},
close: function (arr) {
return arr.length ? arr[arr.length - 1] : (arr.hasNulls ? null : UNDEFINED);
},
// ohlc and range are special cases where a multidimensional array is input and an array is output
ohlc: function (open, high, low, close) {
open = approximations.open(open);
high = approximations.high(high);
low = approximations.low(low);
close = approximations.close(close);
if (typeof open === NUMBER || typeof high === NUMBER || typeof low === NUMBER || typeof close === NUMBER) {
return [open, high, low, close];
}
// else, return is undefined
},
range: function (low, high) {
low = approximations.low(low);
high = approximations.high(high);
if (typeof low === NUMBER || typeof high === NUMBER) {
return [low, high];
}
// else, return is undefined
}
};
/*jslint white:false */
/**
* Takes parallel arrays of x and y data and groups the data into intervals defined by groupPositions, a collection
* of starting x values for each group.
*/
seriesProto.groupData = function (xData, yData, groupPositions, approximation) {
var series = this,
data = series.data,
dataOptions = series.options.data,
groupedXData = [],
groupedYData = [],
dataLength = xData.length,
pointX,
pointY,
groupedY,
handleYData = !!yData, // when grouping the fake extended axis for panning, we don't need to consider y
values = [[], [], [], []],
approximationFn = typeof approximation === 'function' ? approximation : approximations[approximation],
pointArrayMap = series.pointArrayMap,
pointArrayMapLength = pointArrayMap && pointArrayMap.length,
i;
for (i = 0; i <= dataLength; i++) {
// when a new group is entered, summarize and initiate the previous group
while ((groupPositions[1] !== UNDEFINED && xData[i] >= groupPositions[1]) ||
i === dataLength) { // get the last group
// get group x and y
pointX = groupPositions.shift();
groupedY = approximationFn.apply(0, values);
// push the grouped data
if (groupedY !== UNDEFINED) {
groupedXData.push(pointX);
groupedYData.push(groupedY);
}
// reset the aggregate arrays
values[0] = [];
values[1] = [];
values[2] = [];
values[3] = [];
// don't loop beyond the last group
if (i === dataLength) {
break;
}
}
// break out
if (i === dataLength) {
break;
}
// for each raw data point, push it to an array that contains all values for this specific group
if (pointArrayMap) {
var index = series.cropStart + i,
point = (data && data[index]) || series.pointClass.prototype.applyOptions.apply({ series: series }, [dataOptions[index]]),
j,
val;
for (j = 0; j < pointArrayMapLength; j++) {
val = point[pointArrayMap[j]];
if (typeof val === NUMBER) {
values[j].push(val);
} else if (val === null) {
values[j].hasNulls = true;
}
}
} else {
pointY = handleYData ? yData[i] : null;
if (typeof pointY === NUMBER) {
values[0].push(pointY);
} else if (pointY === null) {
values[0].hasNulls = true;
}
}
}
return [groupedXData, groupedYData];
};
/**
* Extend the basic processData method, that crops the data to the current zoom
* range, with data grouping logic.
*/
seriesProto.processData = function () {
var series = this,
chart = series.chart,
options = series.options,
dataGroupingOptions = options[DATA_GROUPING],
groupingEnabled = dataGroupingOptions && pick(dataGroupingOptions.enabled, chart.options._stock),
hasGroupedData;
// run base method
series.forceCrop = groupingEnabled; // #334
// skip if processData returns false or if grouping is disabled (in that order)
if (baseProcessData.apply(series, arguments) === false || !groupingEnabled) {
return;
} else {
series.destroyGroupedData();
}
var i,
processedXData = series.processedXData,
processedYData = series.processedYData,
plotSizeX = chart.plotSizeX,
xAxis = series.xAxis,
groupPixelWidth = series.groupPixelWidth = xAxis.getGroupPixelWidth && xAxis.getGroupPixelWidth(),
nonGroupedPointRange = series.pointRange;
// Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth
if (groupPixelWidth) {
hasGroupedData = true;
series.points = null; // force recreation of point instances in series.translate
var extremes = xAxis.getExtremes(),
xMin = extremes.min,
xMax = extremes.max,
groupIntervalFactor = (xAxis.getGroupIntervalFactor && xAxis.getGroupIntervalFactor(xMin, xMax, processedXData)) || 1,
interval = (groupPixelWidth * (xMax - xMin) / plotSizeX) * groupIntervalFactor,
groupPositions = (xAxis.getNonLinearTimeTicks || getTimeTicks)(
normalizeTimeTickInterval(interval, dataGroupingOptions.units || defaultDataGroupingUnits),
xMin,
xMax,
null,
processedXData,
series.closestPointRange
),
groupedXandY = seriesProto.groupData.apply(series, [processedXData, processedYData, groupPositions, dataGroupingOptions.approximation]),
groupedXData = groupedXandY[0],
groupedYData = groupedXandY[1];
// prevent the smoothed data to spill out left and right, and make
// sure data is not shifted to the left
if (dataGroupingOptions.smoothed) {
i = groupedXData.length - 1;
groupedXData[i] = xMax;
while (i-- && i > 0) {
groupedXData[i] += interval / 2;
}
groupedXData[0] = xMin;
}
// record what data grouping values were used
series.currentDataGrouping = groupPositions.info;
if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
series.pointRange = groupPositions.info.totalRange;
}
series.closestPointRange = groupPositions.info.totalRange;
// set series props
series.processedXData = groupedXData;
series.processedYData = groupedYData;
} else {
series.currentDataGrouping = null;
series.pointRange = nonGroupedPointRange;
}
series.hasGroupedData = hasGroupedData;
};
/**
* Destroy the grouped data points. #622, #740
*/
seriesProto.destroyGroupedData = function () {
var groupedData = this.groupedData;
// clear previous groups
each(groupedData || [], function (point, i) {
if (point) {
groupedData[i] = point.destroy ? point.destroy() : null;
}
});
this.groupedData = null;
};
/**
* Override the generatePoints method by adding a reference to grouped data
*/
seriesProto.generatePoints = function () {
baseGeneratePoints.apply(this);
// record grouped data in order to let it be destroyed the next time processData runs
this.destroyGroupedData(); // #622
this.groupedData = this.hasGroupedData ? this.points : null;
};
/**
* Make the tooltip's header reflect the grouped range
*/
seriesProto.tooltipHeaderFormatter = function (point) {
var series = this,
options = series.options,
tooltipOptions = series.tooltipOptions,
dataGroupingOptions = options.dataGrouping,
xDateFormat = tooltipOptions.xDateFormat,
xDateFormatEnd,
xAxis = series.xAxis,
currentDataGrouping,
dateTimeLabelFormats,
labelFormats,
formattedKey,
n,
ret;
// apply only to grouped series
if (xAxis && xAxis.options.type === 'datetime' && dataGroupingOptions && isNumber(point.key)) {
// set variables
currentDataGrouping = series.currentDataGrouping;
dateTimeLabelFormats = dataGroupingOptions.dateTimeLabelFormats;
// if we have grouped data, use the grouping information to get the right format
if (currentDataGrouping) {
labelFormats = dateTimeLabelFormats[currentDataGrouping.unitName];
if (currentDataGrouping.count === 1) {
xDateFormat = labelFormats[0];
} else {
xDateFormat = labelFormats[1];
xDateFormatEnd = labelFormats[2];
}
// if not grouped, and we don't have set the xDateFormat option, get the best fit,
// so if the least distance between points is one minute, show it, but if the
// least distance is one day, skip hours and minutes etc.
} else if (!xDateFormat && dateTimeLabelFormats) {
for (n in timeUnits) {
if (timeUnits[n] >= xAxis.closestPointRange) {
xDateFormat = dateTimeLabelFormats[n][0];
break;
}
}
}
// now format the key
formattedKey = dateFormat(xDateFormat, point.key);
if (xDateFormatEnd) {
formattedKey += dateFormat(xDateFormatEnd, point.key + currentDataGrouping.totalRange - 1);
}
// return the replaced format
ret = tooltipOptions.headerFormat.replace('{point.key}', formattedKey);
// else, fall back to the regular formatter
} else {
ret = baseTooltipHeaderFormatter.call(series, point);
}
return ret;
};
/**
* Extend the series destroyer
*/
seriesProto.destroy = function () {
var series = this,
groupedData = series.groupedData || [],
i = groupedData.length;
while (i--) {
if (groupedData[i]) {
groupedData[i].destroy();
}
}
baseDestroy.apply(series);
};
// Handle default options for data grouping. This must be set at runtime because some series types are
// defined after this.
wrap(seriesProto, 'setOptions', function (proceed, itemOptions) {
var options = proceed.call(this, itemOptions),
type = this.type,
plotOptions = this.chart.options.plotOptions,
defaultOptions = defaultPlotOptions[type].dataGrouping;
if (specificOptions[type]) { // #1284
if (!defaultOptions) {
defaultOptions = merge(commonOptions, specificOptions[type]);
}
options.dataGrouping = merge(
defaultOptions,
plotOptions.series && plotOptions.series.dataGrouping, // #1228
plotOptions[type].dataGrouping, // Set by the StockChart constructor
itemOptions.dataGrouping
);
}
if (this.chart.options._stock) {
this.requireSorting = true;
}
return options;
});
/**
* Get the data grouping pixel width based on the greatest defined individual width
* of the axis' series, and if whether one of the axes need grouping.
*/
Axis.prototype.getGroupPixelWidth = function () {
var series = this.series,
len = series.length,
i,
groupPixelWidth = 0,
doGrouping = false,
dataLength,
dgOptions;
// If multiple series are compared on the same x axis, give them the same
// group pixel width (#334)
i = len;
while (i--) {
dgOptions = series[i].options.dataGrouping;
if (dgOptions) {
groupPixelWidth = mathMax(groupPixelWidth, dgOptions.groupPixelWidth);
}
}
// If one of the series needs grouping, apply it to all (#1634)
i = len;
while (i--) {
dgOptions = series[i].options.dataGrouping;
if (dgOptions) {
dataLength = (series[i].processedXData || series[i].data).length;
// Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth
if (series[i].groupPixelWidth || dataLength > (this.chart.plotSizeX / groupPixelWidth) || (dataLength && dgOptions.forced)) {
doGrouping = true;
}
}
}
return doGrouping ? groupPixelWidth : 0;
};
/* ****************************************************************************
* End data grouping module *
******************************************************************************//* ****************************************************************************
* Start OHLC series code *
*****************************************************************************/
// 1 - Set default options
defaultPlotOptions.ohlc = merge(defaultPlotOptions.column, {
lineWidth: 1,
tooltip: {
pointFormat: '<span style="color:{series.color};font-weight:bold">{series.name}</span><br/>' +
'Open: {point.open}<br/>' +
'High: {point.high}<br/>' +
'Low: {point.low}<br/>' +
'Close: {point.close}<br/>'
},
states: {
hover: {
lineWidth: 3
}
},
threshold: null
//upColor: undefined
});
// 2 - Create the OHLCSeries object
var OHLCSeries = extendClass(seriesTypes.column, {
type: 'ohlc',
pointArrayMap: ['open', 'high', 'low', 'close'], // array point configs are mapped to this
toYData: function (point) { // return a plain array for speedy calculation
return [point.open, point.high, point.low, point.close];
},
pointValKey: 'high',
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'color',
'stroke-width': 'lineWidth'
},
upColorProp: 'stroke',
/**
* Postprocess mapping between options and SVG attributes
*/
getAttribs: function () {
seriesTypes.column.prototype.getAttribs.apply(this, arguments);
var series = this,
options = series.options,
stateOptions = options.states,
upColor = options.upColor || series.color,
seriesDownPointAttr = merge(series.pointAttr),
upColorProp = series.upColorProp;
seriesDownPointAttr[''][upColorProp] = upColor;
seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || upColor;
seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor;
each(series.points, function (point) {
if (point.open < point.close) {
point.pointAttr = seriesDownPointAttr;
}
});
},
/**
* Translate data points from raw values x and y to plotX and plotY
*/
translate: function () {
var series = this,
yAxis = series.yAxis;
seriesTypes.column.prototype.translate.apply(series);
// do the translation
each(series.points, function (point) {
// the graphics
if (point.open !== null) {
point.plotOpen = yAxis.translate(point.open, 0, 1, 0, 1);
}
if (point.close !== null) {
point.plotClose = yAxis.translate(point.close, 0, 1, 0, 1);
}
});
},
/**
* Draw the data points
*/
drawPoints: function () {
var series = this,
points = series.points,
chart = series.chart,
pointAttr,
plotOpen,
plotClose,
crispCorr,
halfWidth,
path,
graphic,
crispX;
each(points, function (point) {
if (point.plotY !== UNDEFINED) {
graphic = point.graphic;
pointAttr = point.pointAttr[point.selected ? 'selected' : ''];
// crisp vector coordinates
crispCorr = (pointAttr['stroke-width'] % 2) / 2;
crispX = mathRound(point.plotX) + crispCorr;
halfWidth = mathRound(point.shapeArgs.width / 2);
// the vertical stem
path = [
'M',
crispX, mathRound(point.yBottom),
'L',
crispX, mathRound(point.plotY)
];
// open
if (point.open !== null) {
plotOpen = mathRound(point.plotOpen) + crispCorr;
path.push(
'M',
crispX,
plotOpen,
'L',
crispX - halfWidth,
plotOpen
);
}
// close
if (point.close !== null) {
plotClose = mathRound(point.plotClose) + crispCorr;
path.push(
'M',
crispX,
plotClose,
'L',
crispX + halfWidth,
plotClose
);
}
// create and/or update the graphic
if (graphic) {
graphic.animate({ d: path });
} else {
point.graphic = chart.renderer.path(path)
.attr(pointAttr)
.add(series.group);
}
}
});
},
/**
* Disable animation
*/
animate: null
});
seriesTypes.ohlc = OHLCSeries;
/* ****************************************************************************
* End OHLC series code *
*****************************************************************************/
/* ****************************************************************************
* Start Candlestick series code *
*****************************************************************************/
// 1 - set default options
defaultPlotOptions.candlestick = merge(defaultPlotOptions.column, {
lineColor: 'black',
lineWidth: 1,
states: {
hover: {
lineWidth: 2
}
},
tooltip: defaultPlotOptions.ohlc.tooltip,
threshold: null,
upColor: 'white'
// upLineColor: null
});
// 2 - Create the CandlestickSeries object
var CandlestickSeries = extendClass(OHLCSeries, {
type: 'candlestick',
/**
* One-to-one mapping from options to SVG attributes
*/
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
fill: 'color',
stroke: 'lineColor',
'stroke-width': 'lineWidth'
},
upColorProp: 'fill',
/**
* Postprocess mapping between options and SVG attributes
*/
getAttribs: function () {
seriesTypes.ohlc.prototype.getAttribs.apply(this, arguments);
var series = this,
options = series.options,
stateOptions = options.states,
upLineColor = options.upLineColor || options.lineColor,
hoverStroke = stateOptions.hover.upLineColor || upLineColor,
selectStroke = stateOptions.select.upLineColor || upLineColor;
// Add custom line color for points going up (close > open).
// Fill is handled by OHLCSeries' getAttribs.
each(series.points, function (point) {
if (point.open < point.close) {
point.pointAttr[''].stroke = upLineColor;
point.pointAttr.hover.stroke = hoverStroke;
point.pointAttr.select.stroke = selectStroke;
}
});
},
/**
* Draw the data points
*/
drawPoints: function () {
var series = this, //state = series.state,
points = series.points,
chart = series.chart,
pointAttr,
plotOpen,
plotClose,
topBox,
bottomBox,
hasTopWhisker,
hasBottomWhisker,
crispCorr,
crispX,
graphic,
path,
halfWidth;
each(points, function (point) {
graphic = point.graphic;
if (point.plotY !== UNDEFINED) {
pointAttr = point.pointAttr[point.selected ? 'selected' : ''];
// crisp vector coordinates
crispCorr = (pointAttr['stroke-width'] % 2) / 2;
crispX = mathRound(point.plotX) + crispCorr;
plotOpen = point.plotOpen;
plotClose = point.plotClose;
topBox = math.min(plotOpen, plotClose);
bottomBox = math.max(plotOpen, plotClose);
halfWidth = mathRound(point.shapeArgs.width / 2);
hasTopWhisker = mathRound(topBox) !== mathRound(point.plotY);
hasBottomWhisker = bottomBox !== point.yBottom;
topBox = mathRound(topBox) + crispCorr;
bottomBox = mathRound(bottomBox) + crispCorr;
// create the path
path = [
'M',
crispX - halfWidth, bottomBox,
'L',
crispX - halfWidth, topBox,
'L',
crispX + halfWidth, topBox,
'L',
crispX + halfWidth, bottomBox,
'L',
crispX - halfWidth, bottomBox,
'M',
crispX, topBox,
'L',
crispX, hasTopWhisker ? mathRound(point.plotY) : topBox, // #460, #2094
'M',
crispX, bottomBox,
'L',
crispX, hasBottomWhisker ? mathRound(point.yBottom) : bottomBox, // #460, #2094
'Z'
];
if (graphic) {
graphic.animate({ d: path });
} else {
point.graphic = chart.renderer.path(path)
.attr(pointAttr)
.add(series.group)
.shadow(series.options.shadow);
}
}
});
}
});
seriesTypes.candlestick = CandlestickSeries;
/* ****************************************************************************
* End Candlestick series code *
*****************************************************************************/
/* ****************************************************************************
* Start Flags series code *
*****************************************************************************/
var symbols = SVGRenderer.prototype.symbols;
// 1 - set default options
defaultPlotOptions.flags = merge(defaultPlotOptions.column, {
dataGrouping: null,
fillColor: 'white',
lineWidth: 1,
pointRange: 0, // #673
//radius: 2,
shape: 'flag',
stackDistance: 12,
states: {
hover: {
lineColor: 'black',
fillColor: '#FCFFC5'
}
},
style: {
fontSize: '11px',
fontWeight: 'bold',
textAlign: 'center'
},
tooltip: {
pointFormat: '{point.text}<br/>'
},
threshold: null,
y: -30
});
// 2 - Create the CandlestickSeries object
seriesTypes.flags = extendClass(seriesTypes.column, {
type: 'flags',
sorted: false,
noSharedTooltip: true,
takeOrdinalPosition: false, // #1074
forceCrop: true,
/**
* Inherit the initialization from base Series
*/
init: Series.prototype.init,
/**
* One-to-one mapping from options to SVG attributes
*/
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
fill: 'fillColor',
stroke: 'color',
'stroke-width': 'lineWidth',
r: 'radius'
},
/**
* Extend the translate method by placing the point on the related series
*/
translate: function () {
seriesTypes.column.prototype.translate.apply(this);
var series = this,
options = series.options,
chart = series.chart,
points = series.points,
cursor = points.length - 1,
point,
lastPoint,
optionsOnSeries = options.onSeries,
onSeries = optionsOnSeries && chart.get(optionsOnSeries),
step = onSeries && onSeries.options.step,
onData = onSeries && onSeries.points,
i = onData && onData.length,
xAxis = series.xAxis,
xAxisExt = xAxis.getExtremes(),
leftPoint,
lastX,
rightPoint;
// relate to a master series
if (onSeries && onSeries.visible && i) {
lastX = onData[i - 1].x;
// sort the data points
points.sort(function (a, b) {
return (a.x - b.x);
});
while (i-- && points[cursor]) {
point = points[cursor];
leftPoint = onData[i];
if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) {
if (point.x <= lastX) { // #803
point.plotY = leftPoint.plotY;
// interpolate between points, #666
if (leftPoint.x < point.x && !step) {
rightPoint = onData[i + 1];
if (rightPoint && rightPoint.plotY !== UNDEFINED) {
point.plotY +=
((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1
(rightPoint.plotY - leftPoint.plotY); // the y distance
}
}
}
cursor--;
i++; // check again for points in the same x position
if (cursor < 0) {
break;
}
}
}
}
// Add plotY position and handle stacking
each(points, function (point, i) {
// Undefined plotY means the point is either on axis, outside series range or hidden series.
// If the series is outside the range of the x axis it should fall through with
// an undefined plotY, but then we must remove the shapeArgs (#847).
if (point.plotY === UNDEFINED) {
if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range
point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop;
} else {
point.shapeArgs = {}; // 847
}
}
// if multiple flags appear at the same x, order them into a stack
lastPoint = points[i - 1];
if (lastPoint && lastPoint.plotX === point.plotX) {
if (lastPoint.stackIndex === UNDEFINED) {
lastPoint.stackIndex = 0;
}
point.stackIndex = lastPoint.stackIndex + 1;
}
});
},
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
pointAttr,
points = series.points,
chart = series.chart,
renderer = chart.renderer,
plotX,
plotY,
options = series.options,
optionsY = options.y,
shape,
box,
bBox,
i,
point,
graphic,
stackIndex,
crisp = (options.lineWidth % 2 / 2),
anchorX,
anchorY;
i = points.length;
while (i--) {
point = points[i];
plotX = point.plotX + crisp;
stackIndex = point.stackIndex;
shape = point.options.shape || options.shape;
plotY = point.plotY;
if (plotY !== UNDEFINED) {
plotY = point.plotY + optionsY + crisp - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance);
}
anchorX = stackIndex ? UNDEFINED : point.plotX + crisp; // skip connectors for higher level stacked points
anchorY = stackIndex ? UNDEFINED : point.plotY;
graphic = point.graphic;
// only draw the point if y is defined and the flag is within the visible area
if (plotY !== UNDEFINED && plotX >= 0 && plotX < series.xAxis.len) {
// shortcuts
pointAttr = point.pointAttr[point.selected ? 'select' : ''];
if (graphic) { // update
graphic.attr({
x: plotX,
y: plotY,
r: pointAttr.r,
anchorX: anchorX,
anchorY: anchorY
});
} else {
graphic = point.graphic = renderer.label(
point.options.title || options.title || 'A',
plotX,
plotY,
shape,
anchorX,
anchorY,
options.useHTML
)
.css(merge(options.style, point.style))
.attr(pointAttr)
.attr({
align: shape === 'flag' ? 'left' : 'center',
width: options.width,
height: options.height
})
.add(series.group)
.shadow(options.shadow);
}
// get the bounding box
box = graphic.box;
bBox = box.getBBox();
// Set the tooltip anchor position
point.tooltipPos = [plotX, plotY];
} else if (graphic) {
point.graphic = graphic.destroy();
}
}
},
/**
* Extend the column trackers with listeners to expand and contract stacks
*/
drawTracker: function () {
var series = this,
points = series.points;
seriesTypes.column.prototype.drawTracker.apply(this);
// Bring each stacked flag up on mouse over, this allows readability of vertically
// stacked elements as well as tight points on the x axis. #1924.
each(points, function (point) {
var graphic = point.graphic;
if (graphic) {
addEvent(graphic.element, 'mouseover', function () {
// Raise this point
if (point.stackIndex > 0 && !point.raised) {
point._y = graphic.y;
graphic.attr({
y: point._y - 8
});
point.raised = true;
}
// Revert other raised points
each(points, function (otherPoint) {
if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) {
otherPoint.graphic.attr({
y: otherPoint._y
});
otherPoint.raised = false;
}
});
});
}
});
},
/**
* Disable animation
*/
animate: noop
});
// create the flag icon with anchor
symbols.flag = function (x, y, w, h, options) {
var anchorX = (options && options.anchorX) || x,
anchorY = (options && options.anchorY) || y;
return [
'M', anchorX, anchorY,
'L', x, y + h,
x, y,
x + w, y,
x + w, y + h,
x, y + h,
'M', anchorX, anchorY,
'Z'
];
};
// create the circlepin and squarepin icons with anchor
each(['circle', 'square'], function (shape) {
symbols[shape + 'pin'] = function (x, y, w, h, options) {
var anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path = symbols[shape](x, y, w, h),
labelTopOrBottomY;
if (anchorX && anchorY) {
// if the label is below the anchor, draw the connecting line from the top edge of the label
// otherwise start drawing from the bottom edge
labelTopOrBottomY = (y > anchorY) ? y : y + h;
path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY);
}
return path;
};
});
// The symbol callbacks are generated on the SVGRenderer object in all browsers. Even
// VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === VMLRenderer) {
each(['flag', 'circlepin', 'squarepin'], function (shape) {
VMLRenderer.prototype.symbols[shape] = symbols[shape];
});
}
/* ****************************************************************************
* End Flags series code *
*****************************************************************************/
/* ****************************************************************************
* Start Scroller code *
*****************************************************************************/
/*jslint white:true */
var buttonGradient = hash(
LINEAR_GRADIENT, { x1: 0, y1: 0, x2: 0, y2: 1 },
STOPS, [
[0, '#FFF'],
[1, '#CCC']
]
),
units = [].concat(defaultDataGroupingUnits); // copy
// add more resolution to units
units[4] = [DAY, [1, 2, 3, 4]]; // allow more days
units[5] = [WEEK, [1, 2, 3]]; // allow more weeks
extend(defaultOptions, {
navigator: {
//enabled: true,
handles: {
backgroundColor: '#FFF',
borderColor: '#666'
},
height: 40,
margin: 10,
maskFill: 'rgba(255, 255, 255, 0.75)',
outlineColor: '#444',
outlineWidth: 1,
series: {
type: 'areaspline',
color: '#4572A7',
compare: null,
fillOpacity: 0.4,
dataGrouping: {
approximation: 'average',
enabled: true,
groupPixelWidth: 2,
smoothed: true,
units: units
},
dataLabels: {
enabled: false,
zIndex: 2 // #1839
},
id: PREFIX + 'navigator-series',
lineColor: '#4572A7',
lineWidth: 1,
marker: {
enabled: false
},
pointRange: 0,
shadow: false,
threshold: null
},
//top: undefined,
xAxis: {
tickWidth: 0,
lineWidth: 0,
gridLineWidth: 1,
tickPixelInterval: 200,
labels: {
align: 'left',
x: 3,
y: -4
}
},
yAxis: {
gridLineWidth: 0,
startOnTick: false,
endOnTick: false,
minPadding: 0.1,
maxPadding: 0.1,
labels: {
enabled: false
},
title: {
text: null
},
tickWidth: 0
}
},
scrollbar: {
//enabled: true
height: isTouchDevice ? 20 : 14,
barBackgroundColor: buttonGradient,
barBorderRadius: 2,
barBorderWidth: 1,
barBorderColor: '#666',
buttonArrowColor: '#666',
buttonBackgroundColor: buttonGradient,
buttonBorderColor: '#666',
buttonBorderRadius: 2,
buttonBorderWidth: 1,
minWidth: 6,
rifleColor: '#666',
trackBackgroundColor: hash(
LINEAR_GRADIENT, { x1: 0, y1: 0, x2: 0, y2: 1 },
STOPS, [
[0, '#EEE'],
[1, '#FFF']
]
),
trackBorderColor: '#CCC',
trackBorderWidth: 1,
// trackBorderRadius: 0
liveRedraw: hasSVG && !isTouchDevice
}
});
/*jslint white:false */
/**
* The Scroller class
* @param {Object} chart
*/
function Scroller(chart) {
var chartOptions = chart.options,
navigatorOptions = chartOptions.navigator,
navigatorEnabled = navigatorOptions.enabled,
scrollbarOptions = chartOptions.scrollbar,
scrollbarEnabled = scrollbarOptions.enabled,
height = navigatorEnabled ? navigatorOptions.height : 0,
scrollbarHeight = scrollbarEnabled ? scrollbarOptions.height : 0;
this.handles = [];
this.scrollbarButtons = [];
this.elementsToDestroy = []; // Array containing the elements to destroy when Scroller is destroyed
this.chart = chart;
this.setBaseSeries();
this.height = height;
this.scrollbarHeight = scrollbarHeight;
this.scrollbarEnabled = scrollbarEnabled;
this.navigatorEnabled = navigatorEnabled;
this.navigatorOptions = navigatorOptions;
this.scrollbarOptions = scrollbarOptions;
this.outlineHeight = height + scrollbarHeight;
// Run scroller
this.init();
}
Scroller.prototype = {
/**
* Draw one of the handles on the side of the zoomed range in the navigator
* @param {Number} x The x center for the handle
* @param {Number} index 0 for left and 1 for right
*/
drawHandle: function (x, index) {
var scroller = this,
chart = scroller.chart,
renderer = chart.renderer,
elementsToDestroy = scroller.elementsToDestroy,
handles = scroller.handles,
handlesOptions = scroller.navigatorOptions.handles,
attr = {
fill: handlesOptions.backgroundColor,
stroke: handlesOptions.borderColor,
'stroke-width': 1
},
tempElem;
// create the elements
if (!scroller.rendered) {
// the group
handles[index] = renderer.g()
.css({ cursor: 'e-resize' })
.attr({ zIndex: 4 - index }) // zIndex = 3 for right handle, 4 for left
.add();
// the rectangle
tempElem = renderer.rect(-4.5, 0, 9, 16, 3, 1)
.attr(attr)
.add(handles[index]);
elementsToDestroy.push(tempElem);
// the rifles
tempElem = renderer.path([
'M',
-1.5, 4,
'L',
-1.5, 12,
'M',
0.5, 4,
'L',
0.5, 12
]).attr(attr)
.add(handles[index]);
elementsToDestroy.push(tempElem);
}
// Place it
handles[index][chart.isResizing ? 'animate' : 'attr']({
translateX: scroller.scrollerLeft + scroller.scrollbarHeight + parseInt(x, 10),
translateY: scroller.top + scroller.height / 2 - 8
});
},
/**
* Draw the scrollbar buttons with arrows
* @param {Number} index 0 is left, 1 is right
*/
drawScrollbarButton: function (index) {
var scroller = this,
chart = scroller.chart,
renderer = chart.renderer,
elementsToDestroy = scroller.elementsToDestroy,
scrollbarButtons = scroller.scrollbarButtons,
scrollbarHeight = scroller.scrollbarHeight,
scrollbarOptions = scroller.scrollbarOptions,
tempElem;
if (!scroller.rendered) {
scrollbarButtons[index] = renderer.g().add(scroller.scrollbarGroup);
tempElem = renderer.rect(
-0.5,
-0.5,
scrollbarHeight + 1, // +1 to compensate for crispifying in rect method
scrollbarHeight + 1,
scrollbarOptions.buttonBorderRadius,
scrollbarOptions.buttonBorderWidth
).attr({
stroke: scrollbarOptions.buttonBorderColor,
'stroke-width': scrollbarOptions.buttonBorderWidth,
fill: scrollbarOptions.buttonBackgroundColor
}).add(scrollbarButtons[index]);
elementsToDestroy.push(tempElem);
tempElem = renderer.path([
'M',
scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 - 3,
'L',
scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 + 3,
scrollbarHeight / 2 + (index ? 2 : -2), scrollbarHeight / 2
]).attr({
fill: scrollbarOptions.buttonArrowColor
}).add(scrollbarButtons[index]);
elementsToDestroy.push(tempElem);
}
// adjust the right side button to the varying length of the scroll track
if (index) {
scrollbarButtons[index].attr({
translateX: scroller.scrollerWidth - scrollbarHeight
});
}
},
/**
* Render the navigator and scroll bar
* @param {Number} min X axis value minimum
* @param {Number} max X axis value maximum
* @param {Number} pxMin Pixel value minimum
* @param {Number} pxMax Pixel value maximum
*/
render: function (min, max, pxMin, pxMax) {
var scroller = this,
chart = scroller.chart,
renderer = chart.renderer,
navigatorLeft,
navigatorWidth,
scrollerLeft,
scrollerWidth,
scrollbarGroup = scroller.scrollbarGroup,
navigatorGroup = scroller.navigatorGroup,
scrollbar = scroller.scrollbar,
xAxis = scroller.xAxis,
scrollbarTrack = scroller.scrollbarTrack,
scrollbarHeight = scroller.scrollbarHeight,
scrollbarEnabled = scroller.scrollbarEnabled,
navigatorOptions = scroller.navigatorOptions,
scrollbarOptions = scroller.scrollbarOptions,
scrollbarMinWidth = scrollbarOptions.minWidth,
height = scroller.height,
top = scroller.top,
navigatorEnabled = scroller.navigatorEnabled,
outlineWidth = navigatorOptions.outlineWidth,
halfOutline = outlineWidth / 2,
zoomedMin,
zoomedMax,
range,
scrX,
scrWidth,
scrollbarPad = 0,
outlineHeight = scroller.outlineHeight,
barBorderRadius = scrollbarOptions.barBorderRadius,
strokeWidth,
scrollbarStrokeWidth = scrollbarOptions.barBorderWidth,
centerBarX,
outlineTop = top + halfOutline,
verb,
unionExtremes;
// don't render the navigator until we have data (#486)
if (isNaN(min)) {
return;
}
scroller.navigatorLeft = navigatorLeft = pick(
xAxis.left,
chart.plotLeft + scrollbarHeight // in case of scrollbar only, without navigator
);
scroller.navigatorWidth = navigatorWidth = pick(xAxis.len, chart.plotWidth - 2 * scrollbarHeight);
scroller.scrollerLeft = scrollerLeft = navigatorLeft - scrollbarHeight;
scroller.scrollerWidth = scrollerWidth = scrollerWidth = navigatorWidth + 2 * scrollbarHeight;
// Set the scroller x axis extremes to reflect the total. The navigator extremes
// should always be the extremes of the union of all series in the chart as
// well as the navigator series.
if (xAxis.getExtremes) {
unionExtremes = scroller.getUnionExtremes(true);
if (unionExtremes && (unionExtremes.dataMin !== xAxis.min || unionExtremes.dataMax !== xAxis.max)) {
xAxis.setExtremes(unionExtremes.dataMin, unionExtremes.dataMax, true, false);
}
}
// Get the pixel position of the handles
pxMin = pick(pxMin, xAxis.translate(min));
pxMax = pick(pxMax, xAxis.translate(max));
if (isNaN(pxMin) || mathAbs(pxMin) === Infinity) { // Verify (#1851, #2238)
pxMin = 0;
pxMax = scrollerWidth;
}
// handles are allowed to cross, but never exceed the plot area
scroller.zoomedMax = zoomedMax = mathMin(pInt(mathMax(pxMin, pxMax)), navigatorWidth);
scroller.zoomedMin = zoomedMin =
mathMax(scroller.fixedWidth ? zoomedMax - scroller.fixedWidth : pInt(mathMin(pxMin, pxMax)), 0);
scroller.range = range = zoomedMax - zoomedMin;
// on first render, create all elements
if (!scroller.rendered) {
if (navigatorEnabled) {
// draw the navigator group
scroller.navigatorGroup = navigatorGroup = renderer.g('navigator')
.attr({
zIndex: 3
})
.add();
scroller.leftShade = renderer.rect()
.attr({
fill: navigatorOptions.maskFill
}).add(navigatorGroup);
scroller.rightShade = renderer.rect()
.attr({
fill: navigatorOptions.maskFill
}).add(navigatorGroup);
scroller.outline = renderer.path()
.attr({
'stroke-width': outlineWidth,
stroke: navigatorOptions.outlineColor
})
.add(navigatorGroup);
}
if (scrollbarEnabled) {
// draw the scrollbar group
scroller.scrollbarGroup = scrollbarGroup = renderer.g('scrollbar').add();
// the scrollbar track
strokeWidth = scrollbarOptions.trackBorderWidth;
scroller.scrollbarTrack = scrollbarTrack = renderer.rect().attr({
y: -strokeWidth % 2 / 2,
fill: scrollbarOptions.trackBackgroundColor,
stroke: scrollbarOptions.trackBorderColor,
'stroke-width': strokeWidth,
r: scrollbarOptions.trackBorderRadius || 0,
height: scrollbarHeight
}).add(scrollbarGroup);
// the scrollbar itself
scroller.scrollbar = scrollbar = renderer.rect()
.attr({
y: -scrollbarStrokeWidth % 2 / 2,
height: scrollbarHeight,
fill: scrollbarOptions.barBackgroundColor,
stroke: scrollbarOptions.barBorderColor,
'stroke-width': scrollbarStrokeWidth,
r: barBorderRadius
})
.add(scrollbarGroup);
scroller.scrollbarRifles = renderer.path()
.attr({
stroke: scrollbarOptions.rifleColor,
'stroke-width': 1
})
.add(scrollbarGroup);
}
}
// place elements
verb = chart.isResizing ? 'animate' : 'attr';
if (navigatorEnabled) {
scroller.leftShade[verb]({
x: navigatorLeft,
y: top,
width: zoomedMin,
height: height
});
scroller.rightShade[verb]({
x: navigatorLeft + zoomedMax,
y: top,
width: navigatorWidth - zoomedMax,
height: height
});
scroller.outline[verb]({ d: [
M,
scrollerLeft, outlineTop, // left
L,
navigatorLeft + zoomedMin + halfOutline, outlineTop, // upper left of zoomed range
navigatorLeft + zoomedMin + halfOutline, outlineTop + outlineHeight - scrollbarHeight, // lower left of z.r.
M,
navigatorLeft + zoomedMax - halfOutline, outlineTop + outlineHeight - scrollbarHeight, // lower right of z.r.
L,
navigatorLeft + zoomedMax - halfOutline, outlineTop, // upper right of z.r.
scrollerLeft + scrollerWidth, outlineTop // right
]});
// draw handles
scroller.drawHandle(zoomedMin + halfOutline, 0);
scroller.drawHandle(zoomedMax + halfOutline, 1);
}
// draw the scrollbar
if (scrollbarEnabled && scrollbarGroup) {
// draw the buttons
scroller.drawScrollbarButton(0);
scroller.drawScrollbarButton(1);
scrollbarGroup[verb]({
translateX: scrollerLeft,
translateY: mathRound(outlineTop + height)
});
scrollbarTrack[verb]({
width: scrollerWidth
});
// prevent the scrollbar from drawing to small (#1246)
scrX = scrollbarHeight + zoomedMin;
scrWidth = range - scrollbarStrokeWidth;
if (scrWidth < scrollbarMinWidth) {
scrollbarPad = (scrollbarMinWidth - scrWidth) / 2;
scrWidth = scrollbarMinWidth;
scrX -= scrollbarPad;
}
scroller.scrollbarPad = scrollbarPad;
scrollbar[verb]({
x: mathFloor(scrX) + (scrollbarStrokeWidth % 2 / 2),
width: scrWidth
});
centerBarX = scrollbarHeight + zoomedMin + range / 2 - 0.5;
scroller.scrollbarRifles
.attr({
visibility: range > 12 ? VISIBLE : HIDDEN
})[verb]({
d: [
M,
centerBarX - 3, scrollbarHeight / 4,
L,
centerBarX - 3, 2 * scrollbarHeight / 3,
M,
centerBarX, scrollbarHeight / 4,
L,
centerBarX, 2 * scrollbarHeight / 3,
M,
centerBarX + 3, scrollbarHeight / 4,
L,
centerBarX + 3, 2 * scrollbarHeight / 3
]
});
}
scroller.scrollbarPad = scrollbarPad;
scroller.rendered = true;
},
/**
* Set up the mouse and touch events for the navigator and scrollbar
*/
addEvents: function () {
var container = this.chart.container,
mouseDownHandler = this.mouseDownHandler,
mouseMoveHandler = this.mouseMoveHandler,
mouseUpHandler = this.mouseUpHandler,
_events;
// Mouse events
_events = [
[container, 'mousedown', mouseDownHandler],
[container, 'mousemove', mouseMoveHandler],
[document, 'mouseup', mouseUpHandler]
];
// Touch events
if (hasTouch) {
_events.push(
[container, 'touchstart', mouseDownHandler],
[container, 'touchmove', mouseMoveHandler],
[document, 'touchend', mouseUpHandler]
);
}
// Add them all
each(_events, function (args) {
addEvent.apply(null, args);
});
this._events = _events;
},
/**
* Removes the event handlers attached previously with addEvents.
*/
removeEvents: function () {
each(this._events, function (args) {
removeEvent.apply(null, args);
});
this._events = UNDEFINED;
if (this.navigatorEnabled && this.baseSeries) {
removeEvent(this.baseSeries, 'updatedData', this.updatedDataHandler);
}
},
/**
* Initiate the Scroller object
*/
init: function () {
var scroller = this,
chart = scroller.chart,
xAxis,
yAxis,
scrollbarHeight = scroller.scrollbarHeight,
navigatorOptions = scroller.navigatorOptions,
height = scroller.height,
top = scroller.top,
dragOffset,
hasDragged,
bodyStyle = document.body.style,
defaultBodyCursor,
baseSeries = scroller.baseSeries;
/**
* Event handler for the mouse down event.
*/
scroller.mouseDownHandler = function (e) {
e = chart.pointer.normalize(e);
var zoomedMin = scroller.zoomedMin,
zoomedMax = scroller.zoomedMax,
top = scroller.top,
scrollbarHeight = scroller.scrollbarHeight,
scrollerLeft = scroller.scrollerLeft,
scrollerWidth = scroller.scrollerWidth,
navigatorLeft = scroller.navigatorLeft,
navigatorWidth = scroller.navigatorWidth,
scrollbarPad = scroller.scrollbarPad,
range = scroller.range,
chartX = e.chartX,
chartY = e.chartY,
baseXAxis = chart.xAxis[0],
fixedMax,
ext,
handleSensitivity = isTouchDevice ? 10 : 7,
left,
isOnNavigator;
if (chartY > top && chartY < top + height + scrollbarHeight) { // we're vertically inside the navigator
isOnNavigator = !scroller.scrollbarEnabled || chartY < top + height;
// grab the left handle
if (isOnNavigator && math.abs(chartX - zoomedMin - navigatorLeft) < handleSensitivity) {
scroller.grabbedLeft = true;
scroller.otherHandlePos = zoomedMax;
scroller.fixedExtreme = baseXAxis.max;
chart.fixedRange = null;
// grab the right handle
} else if (isOnNavigator && math.abs(chartX - zoomedMax - navigatorLeft) < handleSensitivity) {
scroller.grabbedRight = true;
scroller.otherHandlePos = zoomedMin;
scroller.fixedExtreme = baseXAxis.min;
chart.fixedRange = null;
// grab the zoomed range
} else if (chartX > navigatorLeft + zoomedMin - scrollbarPad && chartX < navigatorLeft + zoomedMax + scrollbarPad) {
scroller.grabbedCenter = chartX;
scroller.fixedWidth = range;
// In SVG browsers, change the cursor. IE6 & 7 produce an error on changing the cursor,
// and IE8 isn't able to show it while dragging anyway.
if (chart.renderer.isSVG) {
defaultBodyCursor = bodyStyle.cursor;
bodyStyle.cursor = 'ew-resize';
}
dragOffset = chartX - zoomedMin;
// shift the range by clicking on shaded areas, scrollbar track or scrollbar buttons
} else if (chartX > scrollerLeft && chartX < scrollerLeft + scrollerWidth) {
if (isOnNavigator) { // center around the clicked point
left = chartX - navigatorLeft - range / 2;
} else { // click on scrollbar
if (chartX < navigatorLeft) { // click left scrollbar button
left = zoomedMin - mathMax(mathMin(10, range), 1);
} else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) {
left = zoomedMin + mathMax(mathMin(10, range), 1);
} else {
// click on scrollbar track, shift the scrollbar by one range
left = chartX < navigatorLeft + zoomedMin ? // on the left
zoomedMin - range :
zoomedMax;
}
}
if (left < 0) {
left = 0;
} else if (left + range >= navigatorWidth) {
left = navigatorWidth - range;
fixedMax = xAxis.dataMax; // #2293
}
if (left !== zoomedMin) { // it has actually moved
scroller.fixedWidth = range; // #1370
ext = xAxis.toFixedRange(left, left + range, null, fixedMax);
baseXAxis.setExtremes(
ext.min,
ext.max,
true,
false,
{ trigger: 'navigator' }
);
}
}
}
};
/**
* Event handler for the mouse move event.
*/
scroller.mouseMoveHandler = function (e) {
var scrollbarHeight = scroller.scrollbarHeight,
navigatorLeft = scroller.navigatorLeft,
navigatorWidth = scroller.navigatorWidth,
scrollerLeft = scroller.scrollerLeft,
scrollerWidth = scroller.scrollerWidth,
range = scroller.range,
chartX;
// In iOS, a mousemove event with e.pageX === 0 is fired when holding the finger
// down in the center of the scrollbar. This should be ignored.
if (e.pageX !== 0) {
e = chart.pointer.normalize(e);
chartX = e.chartX;
// validation for handle dragging
if (chartX < navigatorLeft) {
chartX = navigatorLeft;
} else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) {
chartX = scrollerLeft + scrollerWidth - scrollbarHeight;
}
// drag left handle
if (scroller.grabbedLeft) {
hasDragged = true;
scroller.render(0, 0, chartX - navigatorLeft, scroller.otherHandlePos);
// drag right handle
} else if (scroller.grabbedRight) {
hasDragged = true;
scroller.render(0, 0, scroller.otherHandlePos, chartX - navigatorLeft);
// drag scrollbar or open area in navigator
} else if (scroller.grabbedCenter) {
hasDragged = true;
if (chartX < dragOffset) { // outside left
chartX = dragOffset;
} else if (chartX > navigatorWidth + dragOffset - range) { // outside right
chartX = navigatorWidth + dragOffset - range;
}
scroller.render(0, 0, chartX - dragOffset, chartX - dragOffset + range);
}
if (hasDragged && scroller.scrollbarOptions.liveRedraw) {
setTimeout(function () {
scroller.mouseUpHandler(e);
}, 0);
}
}
};
/**
* Event handler for the mouse up event.
*/
scroller.mouseUpHandler = function (e) {
var ext,
fixedMin,
fixedMax;
if (hasDragged) {
// When dragging one handle, make sure the other one doesn't change
if (scroller.zoomedMin === scroller.otherHandlePos) {
fixedMin = scroller.fixedExtreme;
} else if (scroller.zoomedMax === scroller.otherHandlePos) {
fixedMax = scroller.fixedExtreme;
}
if (scroller.zoomedMax === scroller.navigatorWidth) { // #2341
fixedMax = xAxis.dataMax;
}
ext = xAxis.toFixedRange(scroller.zoomedMin, scroller.zoomedMax, fixedMin, fixedMax);
chart.xAxis[0].setExtremes(
ext.min,
ext.max,
true,
false,
{
trigger: 'navigator',
triggerOp: 'navigator-drag',
DOMEvent: e // #1838
}
);
}
if (e.type !== 'mousemove') {
scroller.grabbedLeft = scroller.grabbedRight = scroller.grabbedCenter = scroller.fixedWidth =
scroller.fixedExtreme = scroller.otherHandlePos = hasDragged = dragOffset = null;
bodyStyle.cursor = defaultBodyCursor || '';
}
};
var xAxisIndex = chart.xAxis.length,
yAxisIndex = chart.yAxis.length;
// make room below the chart
chart.extraBottomMargin = scroller.outlineHeight + navigatorOptions.margin;
if (scroller.navigatorEnabled) {
// an x axis is required for scrollbar also
scroller.xAxis = xAxis = new Axis(chart, merge({
ordinal: baseSeries && baseSeries.xAxis.options.ordinal // inherit base xAxis' ordinal option
}, navigatorOptions.xAxis, {
id: 'navigator-x-axis',
isX: true,
type: 'datetime',
index: xAxisIndex,
height: height,
offset: 0,
offsetLeft: scrollbarHeight,
offsetRight: -scrollbarHeight,
startOnTick: false,
endOnTick: false,
minPadding: 0,
maxPadding: 0,
zoomEnabled: false
}));
scroller.yAxis = yAxis = new Axis(chart, merge(navigatorOptions.yAxis, {
id: 'navigator-y-axis',
alignTicks: false,
height: height,
offset: 0,
index: yAxisIndex,
zoomEnabled: false
}));
// If we have a base series, initialize the navigator series
if (baseSeries || navigatorOptions.series.data) {
scroller.addBaseSeries();
// If not, set up an event to listen for added series
} else if (chart.series.length === 0) {
wrap(chart, 'redraw', function (proceed, animation) {
// We've got one, now add it as base and reset chart.redraw
if (chart.series.length > 0 && !scroller.series) {
scroller.setBaseSeries();
chart.redraw = proceed; // reset
}
proceed.call(chart, animation);
});
}
// in case of scrollbar only, fake an x axis to get translation
} else {
scroller.xAxis = xAxis = {
translate: function (value, reverse) {
var ext = chart.xAxis[0].getExtremes(),
scrollTrackWidth = chart.plotWidth - 2 * scrollbarHeight,
dataMin = ext.dataMin,
valueRange = ext.dataMax - dataMin;
return reverse ?
// from pixel to value
(value * valueRange / scrollTrackWidth) + dataMin :
// from value to pixel
scrollTrackWidth * (value - dataMin) / valueRange;
},
toFixedRange: Axis.prototype.toFixedRange
};
}
/**
* For stock charts, extend the Chart.getMargins method so that we can set the final top position
* of the navigator once the height of the chart, including the legend, is determined. #367.
*/
wrap(chart, 'getMargins', function (proceed) {
var legend = this.legend,
legendOptions = legend.options;
proceed.call(this);
// Compute the top position
scroller.top = top = scroller.navigatorOptions.top ||
this.chartHeight - scroller.height - scroller.scrollbarHeight - this.spacing[2] -
(legendOptions.verticalAlign === 'bottom' && legendOptions.enabled && !legendOptions.floating ?
legend.legendHeight + pick(legendOptions.margin, 10) : 0);
if (xAxis && yAxis) { // false if navigator is disabled (#904)
xAxis.options.top = yAxis.options.top = top;
xAxis.setAxisSize();
yAxis.setAxisSize();
}
});
scroller.addEvents();
},
/**
* Get the union data extremes of the chart - the outer data extremes of the base
* X axis and the navigator axis.
*/
getUnionExtremes: function (returnFalseOnNoBaseSeries) {
var baseAxis = this.chart.xAxis[0],
navAxis = this.xAxis,
navAxisOptions = navAxis.options;
if (!returnFalseOnNoBaseSeries || baseAxis.dataMin !== null) {
return {
dataMin: pick(
navAxisOptions && navAxisOptions.min,
((defined(baseAxis.dataMin) && defined(navAxis.dataMin)) ? mathMin : pick)(baseAxis.dataMin, navAxis.dataMin)
),
dataMax: pick(
navAxisOptions && navAxisOptions.max,
((defined(baseAxis.dataMax) && defined(navAxis.dataMax)) ? mathMax : pick)(baseAxis.dataMax, navAxis.dataMax)
)
};
}
},
/**
* Set the base series. With a bit of modification we should be able to make
* this an API method to be called from the outside
*/
setBaseSeries: function (baseSeriesOption) {
var chart = this.chart;
baseSeriesOption = baseSeriesOption || chart.options.navigator.baseSeries;
// If we're resetting, remove the existing series
if (this.series) {
this.series.remove();
}
// Set the new base series
this.baseSeries = chart.series[baseSeriesOption] ||
(typeof baseSeriesOption === 'string' && chart.get(baseSeriesOption)) ||
chart.series[0];
// When run after render, this.xAxis already exists
if (this.xAxis) {
this.addBaseSeries();
}
},
addBaseSeries: function () {
var baseSeries = this.baseSeries,
baseOptions = baseSeries ? baseSeries.options : {},
baseData = baseOptions.data,
mergedNavSeriesOptions,
navigatorSeriesOptions = this.navigatorOptions.series,
navigatorData;
// remove it to prevent merging one by one
navigatorData = navigatorSeriesOptions.data;
this.hasNavigatorData = !!navigatorData;
// Merge the series options
mergedNavSeriesOptions = merge(baseOptions, navigatorSeriesOptions, {
clip: false,
enableMouseTracking: false,
group: 'nav', // for columns
padXAxis: false,
xAxis: 'navigator-x-axis',
yAxis: 'navigator-y-axis',
name: 'Navigator',
showInLegend: false,
isInternal: true,
visible: true
});
// set the data back
mergedNavSeriesOptions.data = navigatorData || baseData;
// add the series
this.series = this.chart.initSeries(mergedNavSeriesOptions);
// Respond to updated data in the base series.
// Abort if lazy-loading data from the server.
if (baseSeries && this.navigatorOptions.adaptToUpdatedData !== false) {
addEvent(baseSeries, 'updatedData', this.updatedDataHandler);
// Survive Series.update()
baseSeries.userOptions.events = extend(baseSeries.userOptions.event, { updatedData: this.updatedDataHandler });
}
},
updatedDataHandler: function () {
var scroller = this.chart.scroller,
baseSeries = scroller.baseSeries,
baseXAxis = baseSeries.xAxis,
baseExtremes = baseXAxis.getExtremes(),
baseMin = baseExtremes.min,
baseMax = baseExtremes.max,
baseDataMin = baseExtremes.dataMin,
baseDataMax = baseExtremes.dataMax,
range = baseMax - baseMin,
stickToMin,
stickToMax,
newMax,
newMin,
doRedraw,
navigatorSeries = scroller.series,
navXData = navigatorSeries.xData,
hasSetExtremes = !!baseXAxis.setExtremes;
// detect whether to move the range
stickToMax = baseMax >= navXData[navXData.length - 1] - (this.closestPointRange || 0); // #570
stickToMin = baseMin <= baseDataMin;
// set the navigator series data to the new data of the base series
if (!scroller.hasNavigatorData) {
navigatorSeries.options.pointStart = baseSeries.xData[0];
navigatorSeries.setData(baseSeries.options.data, false);
doRedraw = true;
}
// if the zoomed range is already at the min, move it to the right as new data
// comes in
if (stickToMin) {
newMin = baseDataMin;
newMax = newMin + range;
}
// if the zoomed range is already at the max, move it to the right as new data
// comes in
if (stickToMax) {
newMax = baseDataMax;
if (!stickToMin) { // if stickToMin is true, the new min value is set above
newMin = mathMax(newMax - range, navigatorSeries.xData[0]);
}
}
// update the extremes
if (hasSetExtremes && (stickToMin || stickToMax)) {
if (!isNaN(newMin)) {
baseXAxis.setExtremes(newMin, newMax, true, false, { trigger: 'updatedData' });
}
// if it is not at any edge, just move the scroller window to reflect the new series data
} else {
if (doRedraw) {
this.chart.redraw(false);
}
scroller.render(
mathMax(baseMin, baseDataMin),
mathMin(baseMax, baseDataMax)
);
}
},
/**
* Destroys allocated elements.
*/
destroy: function () {
var scroller = this;
// Disconnect events added in addEvents
scroller.removeEvents();
// Destroy properties
each([scroller.xAxis, scroller.yAxis, scroller.leftShade, scroller.rightShade, scroller.outline, scroller.scrollbarTrack, scroller.scrollbarRifles, scroller.scrollbarGroup, scroller.scrollbar], function (prop) {
if (prop && prop.destroy) {
prop.destroy();
}
});
scroller.xAxis = scroller.yAxis = scroller.leftShade = scroller.rightShade = scroller.outline = scroller.scrollbarTrack = scroller.scrollbarRifles = scroller.scrollbarGroup = scroller.scrollbar = null;
// Destroy elements in collection
each([scroller.scrollbarButtons, scroller.handles, scroller.elementsToDestroy], function (coll) {
destroyObjectProperties(coll);
});
}
};
Highcharts.Scroller = Scroller;
/**
* For Stock charts, override selection zooming with some special features because
* X axis zooming is already allowed by the Navigator and Range selector.
*/
wrap(Axis.prototype, 'zoom', function (proceed, newMin, newMax) {
var chart = this.chart,
chartOptions = chart.options,
zoomType = chartOptions.chart.zoomType,
previousZoom,
navigator = chartOptions.navigator,
rangeSelector = chartOptions.rangeSelector,
ret;
if (this.isXAxis && ((navigator && navigator.enabled) ||
(rangeSelector && rangeSelector.enabled))) {
// For x only zooming, fool the chart.zoom method not to create the zoom button
// because the property already exists
if (zoomType === 'x') {
chart.resetZoomButton = 'blocked';
// For y only zooming, ignore the X axis completely
} else if (zoomType === 'y') {
ret = false;
// For xy zooming, record the state of the zoom before zoom selection, then when
// the reset button is pressed, revert to this state
} else if (zoomType === 'xy') {
previousZoom = this.previousZoom;
if (defined(newMin)) {
this.previousZoom = [this.min, this.max];
} else if (previousZoom) {
newMin = previousZoom[0];
newMax = previousZoom[1];
delete this.previousZoom;
}
}
}
return ret !== UNDEFINED ? ret : proceed.call(this, newMin, newMax);
});
// Initialize scroller for stock charts
wrap(Chart.prototype, 'init', function (proceed, options, callback) {
addEvent(this, 'beforeRender', function () {
var options = this.options;
if (options.navigator.enabled || options.scrollbar.enabled) {
this.scroller = new Scroller(this);
}
});
proceed.call(this, options, callback);
});
/* ****************************************************************************
* End Scroller code *
*****************************************************************************/
/* ****************************************************************************
* Start Range Selector code *
*****************************************************************************/
extend(defaultOptions, {
rangeSelector: {
// enabled: true,
// buttons: {Object}
// buttonSpacing: 0,
buttonTheme: {
width: 28,
height: 16,
padding: 1,
r: 0,
stroke: '#68A',
zIndex: 7 // #484, #852
// states: {
// hover: {},
// select: {}
// }
},
inputPosition: {
align: 'right'
},
// inputDateFormat: '%b %e, %Y',
// inputEditDateFormat: '%Y-%m-%d',
// inputEnabled: true,
//inputStyle: {},
labelStyle: {
color: '#666'
}
// selected: undefined
}
});
defaultOptions.lang = merge(defaultOptions.lang, {
rangeSelectorZoom: 'Zoom',
rangeSelectorFrom: 'From',
rangeSelectorTo: 'To'
});
/**
* The object constructor for the range selector
* @param {Object} chart
*/
function RangeSelector(chart) {
// Run RangeSelector
this.init(chart);
}
RangeSelector.prototype = {
/**
* The method to run when one of the buttons in the range selectors is clicked
* @param {Number} i The index of the button
* @param {Object} rangeOptions
* @param {Boolean} redraw
*/
clickButton: function (i, rangeOptions, redraw) {
var rangeSelector = this,
selected = rangeSelector.selected,
chart = rangeSelector.chart,
buttons = rangeSelector.buttons,
baseAxis = chart.xAxis[0],
unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis || {},
dataMin = unionExtremes.dataMin,
dataMax = unionExtremes.dataMax,
newMin,
newMax = baseAxis && mathRound(mathMin(baseAxis.max, pick(dataMax, baseAxis.max))), // #1568
now,
date = new Date(newMax),
type = rangeOptions.type,
count = rangeOptions.count,
baseXAxisOptions,
range = rangeOptions._range,
rangeMin,
year,
timeName;
if (dataMin === null || dataMax === null || // chart has no data, base series is removed
i === rangeSelector.selected) { // same button is clicked twice
return;
}
if (type === 'month' || type === 'year') {
timeName = { month: 'Month', year: 'FullYear'}[type];
date['set' + timeName](date['get' + timeName]() - count);
newMin = date.getTime();
dataMin = pick(dataMin, Number.MIN_VALUE);
if (isNaN(newMin) || newMin < dataMin) {
newMin = dataMin;
newMax = mathMin(newMin + range, dataMax);
} else {
range = newMax - newMin;
}
// Fixed times like minutes, hours, days
} else if (range) {
newMin = mathMax(newMax - range, dataMin);
newMax = mathMin(newMin + range, dataMax);
} else if (type === 'ytd') {
// On user clicks on the buttons, or a delayed action running from the beforeRender
// event (below), the baseAxis is defined.
if (baseAxis) {
// When "ytd" is the pre-selected button for the initial view, its calculation
// is delayed and rerun in the beforeRender event (below). When the series
// are initialized, but before the chart is rendered, we have access to the xData
// array (#942).
if (dataMax === UNDEFINED) {
dataMin = Number.MAX_VALUE;
dataMax = Number.MIN_VALUE;
each(chart.series, function (series) {
var xData = series.xData; // reassign it to the last item
dataMin = mathMin(xData[0], dataMin);
dataMax = mathMax(xData[xData.length - 1], dataMax);
});
redraw = false;
}
now = new Date(dataMax);
year = now.getFullYear();
newMin = rangeMin = mathMax(dataMin || 0, Date.UTC(year, 0, 1));
now = now.getTime();
newMax = mathMin(dataMax || now, now);
// "ytd" is pre-selected. We don't yet have access to processed point and extremes data
// (things like pointStart and pointInterval are missing), so we delay the process (#942)
} else {
addEvent(chart, 'beforeRender', function () {
rangeSelector.clickButton(i, rangeOptions);
});
return;
}
} else if (type === 'all' && baseAxis) {
newMin = dataMin;
newMax = dataMax;
}
// Deselect previous button
if (buttons[selected]) {
buttons[selected].setState(0);
}
// Select this button
if (buttons[i]) {
buttons[i].setState(2);
}
chart.fixedRange = range;
// update the chart
if (!baseAxis) { // axis not yet instanciated
baseXAxisOptions = chart.options.xAxis;
baseXAxisOptions[0] = merge(
baseXAxisOptions[0],
{
range: range,
min: rangeMin
}
);
rangeSelector.selected = i;
} else { // existing axis object; after render time
baseAxis.setExtremes(
newMin,
newMax,
pick(redraw, 1),
0,
{
trigger: 'rangeSelectorButton',
rangeSelectorButton: rangeOptions
}
);
rangeSelector.selected = i;
}
},
/**
* The default buttons for pre-selecting time frames
*/
defaultButtons: [{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 3,
text: '3m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'ytd',
text: 'YTD'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
/**
* Initialize the range selector
*/
init: function (chart) {
var rangeSelector = this,
options = chart.options.rangeSelector,
buttonOptions = options.buttons || [].concat(rangeSelector.defaultButtons),
buttons = rangeSelector.buttons = [],
selectedOption = options.selected,
blurInputs = rangeSelector.blurInputs = function () {
var minInput = rangeSelector.minInput,
maxInput = rangeSelector.maxInput;
if (minInput) {
minInput.blur();
}
if (maxInput) {
maxInput.blur();
}
};
rangeSelector.chart = chart;
chart.extraTopMargin = 25;
rangeSelector.buttonOptions = buttonOptions;
addEvent(chart.container, 'mousedown', blurInputs);
addEvent(chart, 'resize', blurInputs);
// Extend the buttonOptions with actual range
each(buttonOptions, rangeSelector.computeButtonRange);
// zoomed range based on a pre-selected button index
if (selectedOption !== UNDEFINED && buttonOptions[selectedOption]) {
this.clickButton(selectedOption, buttonOptions[selectedOption], false);
}
// normalize the pressed button whenever a new range is selected
addEvent(chart, 'load', function () {
addEvent(chart.xAxis[0], 'afterSetExtremes', function () {
if (chart.fixedRange !== mathRound(this.max - this.min)) {
if (buttons[rangeSelector.selected] && !chart.renderer.forExport) {
buttons[rangeSelector.selected].setState(0);
}
rangeSelector.selected = null;
}
rangeSelector.updateButtonStates();
});
});
},
/**
* Dynamically update the range selector buttons after a new range has been set
*/
updateButtonStates: function () {
var rangeSelector = this,
chart = this.chart,
baseAxis = chart.xAxis[0],
unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis,
dataMin = unionExtremes.dataMin,
dataMax = unionExtremes.dataMax,
selected = rangeSelector.selected,
buttons = rangeSelector.buttons;
each(rangeSelector.buttonOptions, function (rangeOptions, i) {
var range = rangeOptions._range,
// Disable buttons where the range exceeds what is allowed in the current view
isTooGreatRange = range > dataMax - dataMin,
// Disable buttons where the range is smaller than the minimum range
isTooSmallRange = range < baseAxis.minRange,
// Disable the All button if we're already showing all
isAllButAlreadyShowingAll = rangeOptions.type === 'all' && baseAxis.max - baseAxis.min >= dataMax - dataMin &&
buttons[i].state !== 2,
// Disable the YTD button if the complete range is within the same year
isYTDButNotAvailable = rangeOptions.type === 'ytd' && dateFormat('%Y', dataMin) === dateFormat('%Y', dataMax);
// The new zoom area happens to match the range for a button - mark it selected.
// This happens when scrolling across an ordinal gap. It can be seen in the intraday
// demos when selecting 1h and scroll across the night gap.
if (range === mathRound(baseAxis.max - baseAxis.min) && i !== selected) {
rangeSelector.selected = i;
buttons[i].setState(2);
} else if (isTooGreatRange || isTooSmallRange || isAllButAlreadyShowingAll || isYTDButNotAvailable) {
buttons[i].setState(3);
} else if (buttons[i].state === 3) {
buttons[i].setState(0);
}
});
},
/**
* Compute and cache the range for an individual button
*/
computeButtonRange: function (rangeOptions) {
var type = rangeOptions.type,
count = rangeOptions.count || 1,
// these time intervals have a fixed number of milliseconds, as opposed
// to month, ytd and year
fixedTimes = {
millisecond: 1,
second: 1000,
minute: 60 * 1000,
hour: 3600 * 1000,
day: 24 * 3600 * 1000,
week: 7 * 24 * 3600 * 1000
};
// Store the range on the button object
if (fixedTimes[type]) {
rangeOptions._range = fixedTimes[type] * count;
} else if (type === 'month' || type === 'year') {
rangeOptions._range = { month: 30, year: 365 }[type] * 24 * 36e5 * count;
}
},
/**
* Set the internal and displayed value of a HTML input for the dates
* @param {String} name
* @param {Number} time
*/
setInputValue: function (name, time) {
var options = this.chart.options.rangeSelector;
if (defined(time)) {
this[name + 'Input'].HCTime = time;
}
this[name + 'Input'].value = dateFormat(options.inputEditDateFormat || '%Y-%m-%d', this[name + 'Input'].HCTime);
this[name + 'DateBox'].attr({ text: dateFormat(options.inputDateFormat || '%b %e, %Y', this[name + 'Input'].HCTime) });
},
/**
* Draw either the 'from' or the 'to' HTML input box of the range selector
* @param {Object} name
*/
drawInput: function (name) {
var rangeSelector = this,
chart = rangeSelector.chart,
chartStyle = chart.options.chart.style,
renderer = chart.renderer,
options = chart.options.rangeSelector,
lang = defaultOptions.lang,
div = rangeSelector.div,
isMin = name === 'min',
input,
label,
dateBox,
inputGroup = this.inputGroup;
// Create the text label
this[name + 'Label'] = label = renderer.label(lang[isMin ? 'rangeSelectorFrom' : 'rangeSelectorTo'], this.inputGroup.offset)
.attr({
padding: 1
})
.css(merge(chartStyle, options.labelStyle))
.add(inputGroup);
inputGroup.offset += label.width + 5;
// Create an SVG label that shows updated date ranges and and records click events that
// bring in the HTML input.
this[name + 'DateBox'] = dateBox = renderer.label('', inputGroup.offset)
.attr({
padding: 1,
width: options.inputBoxWidth || 90,
height: options.inputBoxHeight || 16,
stroke: options.inputBoxBorderColor || 'silver',
'stroke-width': 1
})
.css(merge({
textAlign: 'center'
}, chartStyle, options.inputStyle))
.on('click', function () {
rangeSelector[name + 'Input'].focus();
})
.add(inputGroup);
inputGroup.offset += dateBox.width + (isMin ? 10 : 0);
// Create the HTML input element. This is rendered as 1x1 pixel then set to the right size
// when focused.
this[name + 'Input'] = input = createElement('input', {
name: name,
className: PREFIX + 'range-selector',
type: 'text'
}, extend({
position: ABSOLUTE,
border: 0,
width: '1px', // Chrome needs a pixel to see it
height: '1px',
padding: 0,
textAlign: 'center',
fontSize: chartStyle.fontSize,
fontFamily: chartStyle.fontFamily,
top: chart.plotTop + PX // prevent jump on focus in Firefox
}, options.inputStyle), div);
// Blow up the input box
input.onfocus = function () {
css(this, {
left: (inputGroup.translateX + dateBox.x) + PX,
top: inputGroup.translateY + PX,
width: (dateBox.width - 2) + PX,
height: (dateBox.height - 2) + PX,
border: '2px solid silver'
});
};
// Hide away the input box
input.onblur = function () {
css(this, {
border: 0,
width: '1px',
height: '1px'
});
rangeSelector.setInputValue(name);
};
// handle changes in the input boxes
input.onchange = function () {
var inputValue = input.value,
value = (options.inputDateParser || Date.parse)(inputValue),
extremes = chart.xAxis[0].getExtremes();
// If the value isn't parsed directly to a value by the browser's Date.parse method,
// like YYYY-MM-DD in IE, try parsing it a different way
if (isNaN(value)) {
value = inputValue.split('-');
value = Date.UTC(pInt(value[0]), pInt(value[1]) - 1, pInt(value[2]));
}
if (!isNaN(value)) {
// Correct for timezone offset (#433)
if (!defaultOptions.global.useUTC) {
value = value + new Date().getTimezoneOffset() * 60 * 1000;
}
// Set the extremes
if ((isMin && (value >= extremes.dataMin && value <= rangeSelector.maxInput.HCTime)) ||
(!isMin && (value <= extremes.dataMax && value >= rangeSelector.minInput.HCTime))) {
chart.xAxis[0].setExtremes(
isMin ? value : extremes.min,
isMin ? extremes.max : value,
UNDEFINED,
UNDEFINED,
{ trigger: 'rangeSelectorInput' }
);
}
}
};
},
/**
* Render the range selector including the buttons and the inputs. The first time render
* is called, the elements are created and positioned. On subsequent calls, they are
* moved and updated.
* @param {Number} min X axis minimum
* @param {Number} max X axis maximum
*/
render: function (min, max) {
var rangeSelector = this,
chart = rangeSelector.chart,
renderer = chart.renderer,
container = chart.container,
chartOptions = chart.options,
navButtonOptions = chartOptions.exporting && chartOptions.navigation && chartOptions.navigation.buttonOptions,
options = chartOptions.rangeSelector,
buttons = rangeSelector.buttons,
lang = defaultOptions.lang,
div = rangeSelector.div,
inputGroup = rangeSelector.inputGroup,
buttonTheme = options.buttonTheme,
inputEnabled = options.inputEnabled !== false,
states = buttonTheme && buttonTheme.states,
plotLeft = chart.plotLeft,
yAlign,
buttonLeft;
// create the elements
if (!rangeSelector.rendered) {
rangeSelector.zoomText = renderer.text(lang.rangeSelectorZoom, plotLeft, chart.plotTop - 10)
.css(options.labelStyle)
.add();
// button starting position
buttonLeft = plotLeft + rangeSelector.zoomText.getBBox().width + 5;
each(rangeSelector.buttonOptions, function (rangeOptions, i) {
buttons[i] = renderer.button(
rangeOptions.text,
buttonLeft,
chart.plotTop - 25,
function () {
rangeSelector.clickButton(i, rangeOptions);
rangeSelector.isActive = true;
},
buttonTheme,
states && states.hover,
states && states.select
)
.css({
textAlign: 'center'
})
.add();
// increase button position for the next button
buttonLeft += buttons[i].width + (options.buttonSpacing || 0);
if (rangeSelector.selected === i) {
buttons[i].setState(2);
}
});
rangeSelector.updateButtonStates();
// first create a wrapper outside the container in order to make
// the inputs work and make export correct
if (inputEnabled) {
rangeSelector.div = div = createElement('div', null, {
position: 'relative',
height: 0,
zIndex: 1 // above container
});
container.parentNode.insertBefore(div, container);
// Create the group to keep the inputs
rangeSelector.inputGroup = inputGroup = renderer.g('input-group')
.add();
inputGroup.offset = 0;
rangeSelector.drawInput('min');
rangeSelector.drawInput('max');
}
}
if (inputEnabled) {
// Update the alignment to the updated spacing box
yAlign = chart.plotTop - 35;
inputGroup.align(extend({
y: yAlign,
width: inputGroup.offset,
// detect collision with the exporting buttons
x: navButtonOptions && (yAlign < (navButtonOptions.y || 0) + navButtonOptions.height - chart.spacing[0]) ?
-40 : 0
}, options.inputPosition), true, chart.spacingBox);
// Set or reset the input values
rangeSelector.setInputValue('min', min);
rangeSelector.setInputValue('max', max);
}
rangeSelector.rendered = true;
},
/**
* Destroys allocated elements.
*/
destroy: function () {
var minInput = this.minInput,
maxInput = this.maxInput,
chart = this.chart,
blurInputs = this.blurInputs,
key;
removeEvent(chart.container, 'mousedown', blurInputs);
removeEvent(chart, 'resize', blurInputs);
// Destroy elements in collections
destroyObjectProperties(this.buttons);
// Clear input element events
if (minInput) {
minInput.onfocus = minInput.onblur = minInput.onchange = null;
}
if (maxInput) {
maxInput.onfocus = maxInput.onblur = maxInput.onchange = null;
}
// Destroy HTML and SVG elements
for (key in this) {
if (this[key] && key !== 'chart') {
if (this[key].destroy) { // SVGElement
this[key].destroy();
} else if (this[key].nodeType) { // HTML element
discardElement(this[key]);
}
}
this[key] = null;
}
}
};
/**
* Add logic to normalize the zoomed range in order to preserve the pressed state of range selector buttons
*/
Axis.prototype.toFixedRange = function (pxMin, pxMax, fixedMin, fixedMax) {
var fixedRange = this.chart && this.chart.fixedRange,
newMin = pick(fixedMin, this.translate(pxMin, true)),
newMax = pick(fixedMax, this.translate(pxMax, true));
// If the difference between the fixed range and the actual requested range is
// too great, the user is dragging across an ordinal gap, and we need to release
// the range selector button.
if (fixedRange && (newMax - newMin) / fixedRange < 1.3) {
if (fixedMax) {
newMin = newMax - fixedRange;
} else {
newMax = newMin + fixedRange;
}
}
return {
min: newMin,
max: newMax
};
};
// Initialize scroller for stock charts
wrap(Chart.prototype, 'init', function (proceed, options, callback) {
addEvent(this, 'init', function () {
if (this.options.rangeSelector.enabled) {
this.rangeSelector = new RangeSelector(this);
}
});
proceed.call(this, options, callback);
});
Highcharts.RangeSelector = RangeSelector;
/* ****************************************************************************
* End Range Selector code *
*****************************************************************************/
Chart.prototype.callbacks.push(function (chart) {
var extremes,
scroller = chart.scroller,
rangeSelector = chart.rangeSelector;
function renderScroller() {
extremes = chart.xAxis[0].getExtremes();
scroller.render(extremes.min, extremes.max);
}
function renderRangeSelector() {
extremes = chart.xAxis[0].getExtremes();
if (!isNaN(extremes.min)) {
rangeSelector.render(extremes.min, extremes.max);
}
}
function afterSetExtremesHandlerScroller(e) {
if (e.triggerOp !== 'navigator-drag') {
scroller.render(e.min, e.max);
}
}
function afterSetExtremesHandlerRangeSelector(e) {
rangeSelector.render(e.min, e.max);
}
function destroyEvents() {
if (scroller) {
removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller);
}
if (rangeSelector) {
removeEvent(chart, 'resize', renderRangeSelector);
removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector);
}
}
// initiate the scroller
if (scroller) {
// redraw the scroller on setExtremes
addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller);
// redraw the scroller on chart resize or box resize
wrap(chart, 'drawChartBox', function (proceed) {
var isDirtyBox = this.isDirtyBox;
proceed.call(this);
if (isDirtyBox) {
renderScroller();
}
});
// do it now
renderScroller();
}
if (rangeSelector) {
// redraw the scroller on setExtremes
addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector);
// redraw the scroller chart resize
addEvent(chart, 'resize', renderRangeSelector);
// do it now
renderRangeSelector();
}
// Remove resize/afterSetExtremes at chart destroy
addEvent(chart, 'destroy', destroyEvents);
});
/**
* A wrapper for Chart with all the default values for a Stock chart
*/
Highcharts.StockChart = function (options, callback) {
var seriesOptions = options.series, // to increase performance, don't merge the data
opposite,
// Always disable startOnTick:true on the main axis when the navigator is enabled (#1090)
navigatorEnabled = pick(options.navigator && options.navigator.enabled, true),
disableStartOnTick = navigatorEnabled ? {
startOnTick: false,
endOnTick: false
} : null,
lineOptions = {
marker: {
enabled: false,
states: {
hover: {
radius: 5
}
}
},
// gapSize: 0,
states: {
hover: {
lineWidth: 2
}
}
},
columnOptions = {
shadow: false,
borderWidth: 0
};
// apply X axis options to both single and multi y axes
options.xAxis = map(splat(options.xAxis || {}), function (xAxisOptions) {
return merge({ // defaults
minPadding: 0,
maxPadding: 0,
ordinal: true,
title: {
text: null
},
labels: {
overflow: 'justify'
},
showLastLabel: true
}, xAxisOptions, // user options
{ // forced options
type: 'datetime',
categories: null
},
disableStartOnTick
);
});
// apply Y axis options to both single and multi y axes
options.yAxis = map(splat(options.yAxis || {}), function (yAxisOptions) {
opposite = yAxisOptions.opposite;
return merge({ // defaults
labels: {
align: opposite ? 'right' : 'left',
x: opposite ? -2 : 2,
y: -2
},
showLastLabel: false,
title: {
text: null
}
}, yAxisOptions // user options
);
});
options.series = null;
options = merge({
chart: {
panning: true,
pinchType: 'x'
},
navigator: {
enabled: true
},
scrollbar: {
enabled: true
},
rangeSelector: {
enabled: true
},
title: {
text: null
},
tooltip: {
shared: true,
crosshairs: true
},
legend: {
enabled: false
},
plotOptions: {
line: lineOptions,
spline: lineOptions,
area: lineOptions,
areaspline: lineOptions,
arearange: lineOptions,
areasplinerange: lineOptions,
column: columnOptions,
columnrange: columnOptions,
candlestick: columnOptions,
ohlc: columnOptions
}
},
options, // user's options
{ // forced options
_stock: true, // internal flag
chart: {
inverted: false
}
});
options.series = seriesOptions;
return new Chart(options, callback);
};
// Implement the pinchType option
wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
var pinchType = options.chart.pinchType || '';
proceed.call(this, chart, options);
// Pinch status
this.pinchX = this.pinchHor = pinchType.indexOf('x') !== -1;
this.pinchY = this.pinchVert = pinchType.indexOf('y') !== -1;
});
/* ****************************************************************************
* Start value compare logic *
*****************************************************************************/
var seriesInit = seriesProto.init,
seriesProcessData = seriesProto.processData,
pointTooltipFormatter = Point.prototype.tooltipFormatter;
/**
* Extend series.init by adding a method to modify the y value used for plotting
* on the y axis. This method is called both from the axis when finding dataMin
* and dataMax, and from the series.translate method.
*/
seriesProto.init = function () {
// Call base method
seriesInit.apply(this, arguments);
// Set comparison mode
this.setCompare(this.options.compare);
};
/**
* The setCompare method can be called also from the outside after render time
*/
seriesProto.setCompare = function (compare) {
// Set or unset the modifyValue method
this.modifyValue = (compare === 'value' || compare === 'percent') ? function (value, point) {
var compareValue = this.compareValue;
// get the modified value
value = compare === 'value' ?
value - compareValue : // compare value
value = 100 * (value / compareValue) - 100; // compare percent
// record for tooltip etc.
if (point) {
point.change = value;
}
return value;
} : null;
// Mark dirty
if (this.chart.hasRendered) {
this.isDirty = true;
}
};
/**
* Extend series.processData by finding the first y value in the plot area,
* used for comparing the following values
*/
seriesProto.processData = function () {
var series = this,
i = 0,
processedXData,
processedYData,
length;
// call base method
seriesProcessData.apply(this, arguments);
if (series.xAxis && series.processedYData) { // not pies
// local variables
processedXData = series.processedXData;
processedYData = series.processedYData;
length = processedYData.length;
// find the first value for comparison
for (; i < length; i++) {
if (typeof processedYData[i] === NUMBER && processedXData[i] >= series.xAxis.min) {
series.compareValue = processedYData[i];
break;
}
}
}
};
/**
* Modify series extremes
*/
wrap(seriesProto, 'getExtremes', function (proceed) {
proceed.call(this);
if (this.modifyValue) {
this.dataMax = this.modifyValue(this.dataMax);
this.dataMin = this.modifyValue(this.dataMin);
}
});
/**
* Add a utility method, setCompare, to the Y axis
*/
Axis.prototype.setCompare = function (compare, redraw) {
if (!this.isXAxis) {
each(this.series, function (series) {
series.setCompare(compare);
});
if (pick(redraw, true)) {
this.chart.redraw();
}
}
};
/**
* Extend the tooltip formatter by adding support for the point.change variable
* as well as the changeDecimals option
*/
Point.prototype.tooltipFormatter = function (pointFormat) {
var point = this;
pointFormat = pointFormat.replace(
'{point.change}',
(point.change > 0 ? '+' : '') + numberFormat(point.change, pick(point.series.tooltipOptions.changeDecimals, 2))
);
return pointTooltipFormatter.apply(this, [pointFormat]);
};
/* ****************************************************************************
* End value compare logic *
*****************************************************************************/
/* ****************************************************************************
* Start ordinal axis logic *
*****************************************************************************/
(function () {
var baseInit = seriesProto.init,
baseGetSegments = seriesProto.getSegments;
seriesProto.init = function () {
var series = this,
chart,
xAxis;
// call base method
baseInit.apply(series, arguments);
// chart and xAxis are set in base init
chart = series.chart;
xAxis = series.xAxis;
// Destroy the extended ordinal index on updated data
if (xAxis && xAxis.options.ordinal) {
addEvent(series, 'updatedData', function () {
delete xAxis.ordinalIndex;
});
}
/**
* Extend the ordinal axis object. If we rewrite the axis object to a prototype model,
* we should add these properties to the prototype instead.
*/
if (xAxis && xAxis.options.ordinal && !xAxis.hasOrdinalExtension) {
xAxis.hasOrdinalExtension = true;
/**
* Calculate the ordinal positions before tick positions are calculated.
* TODO: When we rewrite Axis to use a prototype model, this should be implemented
* as a method extension to avoid overhead in the core.
*/
xAxis.beforeSetTickPositions = function () {
var axis = this,
len,
ordinalPositions = [],
useOrdinal = false,
dist,
extremes = axis.getExtremes(),
min = extremes.min,
max = extremes.max,
minIndex,
maxIndex,
slope,
i;
// apply the ordinal logic
if (axis.options.ordinal) {
each(axis.series, function (series, i) {
if (series.visible !== false && series.takeOrdinalPosition !== false) {
// concatenate the processed X data into the existing positions, or the empty array
ordinalPositions = ordinalPositions.concat(series.processedXData);
len = ordinalPositions.length;
// remove duplicates (#1588)
ordinalPositions.sort(function (a, b) {
return a - b; // without a custom function it is sorted as strings
});
if (len) {
i = len - 1;
while (i--) {
if (ordinalPositions[i] === ordinalPositions[i + 1]) {
ordinalPositions.splice(i, 1);
}
}
}
}
});
// cache the length
len = ordinalPositions.length;
// Check if we really need the overhead of mapping axis data against the ordinal positions.
// If the series consist of evenly spaced data any way, we don't need any ordinal logic.
if (len > 2) { // two points have equal distance by default
dist = ordinalPositions[1] - ordinalPositions[0];
i = len - 1;
while (i-- && !useOrdinal) {
if (ordinalPositions[i + 1] - ordinalPositions[i] !== dist) {
useOrdinal = true;
}
}
// When zooming in on a week, prevent axis padding for weekends even though the data within
// the week is evenly spaced.
if (ordinalPositions[0] - min > dist || max - ordinalPositions[ordinalPositions.length - 1] > dist) {
useOrdinal = true;
}
}
// Record the slope and offset to compute the linear values from the array index.
// Since the ordinal positions may exceed the current range, get the start and
// end positions within it (#719, #665b)
if (useOrdinal) {
// Register
axis.ordinalPositions = ordinalPositions;
// This relies on the ordinalPositions being set. Use mathMax and mathMin to prevent
// padding on either sides of the data.
minIndex = xAxis.val2lin(mathMax(min, ordinalPositions[0]), true);
maxIndex = xAxis.val2lin(mathMin(max, ordinalPositions[ordinalPositions.length - 1]), true);
// Set the slope and offset of the values compared to the indices in the ordinal positions
axis.ordinalSlope = slope = (max - min) / (maxIndex - minIndex);
axis.ordinalOffset = min - (minIndex * slope);
} else {
axis.ordinalPositions = axis.ordinalSlope = axis.ordinalOffset = UNDEFINED;
}
}
};
/**
* Translate from a linear axis value to the corresponding ordinal axis position. If there
* are no gaps in the ordinal axis this will be the same. The translated value is the value
* that the point would have if the axis were linear, using the same min and max.
*
* @param Number val The axis value
* @param Boolean toIndex Whether to return the index in the ordinalPositions or the new value
*/
xAxis.val2lin = function (val, toIndex) {
var axis = this,
ordinalPositions = axis.ordinalPositions;
if (!ordinalPositions) {
return val;
} else {
var ordinalLength = ordinalPositions.length,
i,
distance,
ordinalIndex;
// first look for an exact match in the ordinalpositions array
i = ordinalLength;
while (i--) {
if (ordinalPositions[i] === val) {
ordinalIndex = i;
break;
}
}
// if that failed, find the intermediate position between the two nearest values
i = ordinalLength - 1;
while (i--) {
if (val > ordinalPositions[i] || i === 0) { // interpolate
distance = (val - ordinalPositions[i]) / (ordinalPositions[i + 1] - ordinalPositions[i]); // something between 0 and 1
ordinalIndex = i + distance;
break;
}
}
return toIndex ?
ordinalIndex :
axis.ordinalSlope * (ordinalIndex || 0) + axis.ordinalOffset;
}
};
/**
* Translate from linear (internal) to axis value
*
* @param Number val The linear abstracted value
* @param Boolean fromIndex Translate from an index in the ordinal positions rather than a value
*/
xAxis.lin2val = function (val, fromIndex) {
var axis = this,
ordinalPositions = axis.ordinalPositions;
if (!ordinalPositions) { // the visible range contains only equally spaced values
return val;
} else {
var ordinalSlope = axis.ordinalSlope,
ordinalOffset = axis.ordinalOffset,
i = ordinalPositions.length - 1,
linearEquivalentLeft,
linearEquivalentRight,
distance;
// Handle the case where we translate from the index directly, used only
// when panning an ordinal axis
if (fromIndex) {
if (val < 0) { // out of range, in effect panning to the left
val = ordinalPositions[0];
} else if (val > i) { // out of range, panning to the right
val = ordinalPositions[i];
} else { // split it up
i = mathFloor(val);
distance = val - i; // the decimal
}
// Loop down along the ordinal positions. When the linear equivalent of i matches
// an ordinal position, interpolate between the left and right values.
} else {
while (i--) {
linearEquivalentLeft = (ordinalSlope * i) + ordinalOffset;
if (val >= linearEquivalentLeft) {
linearEquivalentRight = (ordinalSlope * (i + 1)) + ordinalOffset;
distance = (val - linearEquivalentLeft) / (linearEquivalentRight - linearEquivalentLeft); // something between 0 and 1
break;
}
}
}
// If the index is within the range of the ordinal positions, return the associated
// or interpolated value. If not, just return the value
return distance !== UNDEFINED && ordinalPositions[i] !== UNDEFINED ?
ordinalPositions[i] + (distance ? distance * (ordinalPositions[i + 1] - ordinalPositions[i]) : 0) :
val;
}
};
/**
* Get the ordinal positions for the entire data set. This is necessary in chart panning
* because we need to find out what points or data groups are available outside the
* visible range. When a panning operation starts, if an index for the given grouping
* does not exists, it is created and cached. This index is deleted on updated data, so
* it will be regenerated the next time a panning operation starts.
*/
xAxis.getExtendedPositions = function () {
var grouping = xAxis.series[0].currentDataGrouping,
ordinalIndex = xAxis.ordinalIndex,
key = grouping ? grouping.count + grouping.unitName : 'raw',
extremes = xAxis.getExtremes(),
fakeAxis,
fakeSeries;
// If this is the first time, or the ordinal index is deleted by updatedData,
// create it.
if (!ordinalIndex) {
ordinalIndex = xAxis.ordinalIndex = {};
}
if (!ordinalIndex[key]) {
// Create a fake axis object where the extended ordinal positions are emulated
fakeAxis = {
series: [],
getExtremes: function () {
return {
min: extremes.dataMin,
max: extremes.dataMax
};
},
options: {
ordinal: true
}
};
// Add the fake series to hold the full data, then apply processData to it
each(xAxis.series, function (series) {
fakeSeries = {
xAxis: fakeAxis,
xData: series.xData,
chart: chart,
destroyGroupedData: noop
};
fakeSeries.options = {
dataGrouping : grouping ? {
enabled: true,
forced: true,
approximation: 'open', // doesn't matter which, use the fastest
units: [[grouping.unitName, [grouping.count]]]
} : {
enabled: false
}
};
series.processData.apply(fakeSeries);
fakeAxis.series.push(fakeSeries);
});
// Run beforeSetTickPositions to compute the ordinalPositions
xAxis.beforeSetTickPositions.apply(fakeAxis);
// Cache it
ordinalIndex[key] = fakeAxis.ordinalPositions;
}
return ordinalIndex[key];
};
/**
* Find the factor to estimate how wide the plot area would have been if ordinal
* gaps were included. This value is used to compute an imagined plot width in order
* to establish the data grouping interval.
*
* A real world case is the intraday-candlestick
* example. Without this logic, it would show the correct data grouping when viewing
* a range within each day, but once moving the range to include the gap between two
* days, the interval would include the cut-away night hours and the data grouping
* would be wrong. So the below method tries to compensate by identifying the most
* common point interval, in this case days.
*
* An opposite case is presented in issue #718. We have a long array of daily data,
* then one point is appended one hour after the last point. We expect the data grouping
* not to change.
*
* In the future, if we find cases where this estimation doesn't work optimally, we
* might need to add a second pass to the data grouping logic, where we do another run
* with a greater interval if the number of data groups is more than a certain fraction
* of the desired group count.
*/
xAxis.getGroupIntervalFactor = function (xMin, xMax, processedXData) {
var i = 0,
len = processedXData.length,
distances = [],
median;
// Register all the distances in an array
for (; i < len - 1; i++) {
distances[i] = processedXData[i + 1] - processedXData[i];
}
// Sort them and find the median
distances.sort(function (a, b) {
return a - b;
});
median = distances[mathFloor(len / 2)];
// Compensate for series that don't extend through the entire axis extent. #1675.
xMin = mathMax(xMin, processedXData[0]);
xMax = mathMin(xMax, processedXData[len - 1]);
// Return the factor needed for data grouping
return (len * median) / (xMax - xMin);
};
/**
* Make the tick intervals closer because the ordinal gaps make the ticks spread out or cluster
*/
xAxis.postProcessTickInterval = function (tickInterval) {
// TODO: http://jsfiddle.net/highcharts/FQm4E/1/
// This is a case where this algorithm doesn't work optimally. In this case, the
// tick labels are spread out per week, but all the gaps reside within weeks. So
// we have a situation where the labels are courser than the ordinal gaps, and
// thus the tick interval should not be altered
var ordinalSlope = this.ordinalSlope;
return ordinalSlope ?
tickInterval / (ordinalSlope / xAxis.closestPointRange) :
tickInterval;
};
/**
* In an ordinal axis, there might be areas with dense consentrations of points, then large
* gaps between some. Creating equally distributed ticks over this entire range
* may lead to a huge number of ticks that will later be removed. So instead, break the
* positions up in segments, find the tick positions for each segment then concatenize them.
* This method is used from both data grouping logic and X axis tick position logic.
*/
xAxis.getNonLinearTimeTicks = function (normalizedInterval, min, max, startOfWeek, positions, closestDistance, findHigherRanks) {
var start = 0,
end = 0,
segmentPositions,
higherRanks = {},
hasCrossedHigherRank,
info,
posLength,
outsideMax,
groupPositions = [],
lastGroupPosition = -Number.MAX_VALUE,
tickPixelIntervalOption = xAxis.options.tickPixelInterval;
// The positions are not always defined, for example for ordinal positions when data
// has regular interval (#1557, #2090)
if (!positions || positions.length < 3 || min === UNDEFINED) {
return getTimeTicks(normalizedInterval, min, max, startOfWeek);
}
// Analyze the positions array to split it into segments on gaps larger than 5 times
// the closest distance. The closest distance is already found at this point, so
// we reuse that instead of computing it again.
posLength = positions.length;
for (; end < posLength; end++) {
outsideMax = end && positions[end - 1] > max;
if (positions[end] < min) { // Set the last position before min
start = end;
}
if (end === posLength - 1 || positions[end + 1] - positions[end] > closestDistance * 5 || outsideMax) {
// For each segment, calculate the tick positions from the getTimeTicks utility
// function. The interval will be the same regardless of how long the segment is.
if (positions[end] > lastGroupPosition) { // #1475
segmentPositions = getTimeTicks(normalizedInterval, positions[start], positions[end], startOfWeek);
// Prevent duplicate groups, for example for multiple segments within one larger time frame (#1475)
while (segmentPositions.length && segmentPositions[0] <= lastGroupPosition) {
segmentPositions.shift();
}
if (segmentPositions.length) {
lastGroupPosition = segmentPositions[segmentPositions.length - 1];
}
groupPositions = groupPositions.concat(segmentPositions);
}
// Set start of next segment
start = end + 1;
}
if (outsideMax) {
break;
}
}
// Get the grouping info from the last of the segments. The info is the same for
// all segments.
info = segmentPositions.info;
// Optionally identify ticks with higher rank, for example when the ticks
// have crossed midnight.
if (findHigherRanks && info.unitRange <= timeUnits[HOUR]) {
end = groupPositions.length - 1;
// Compare points two by two
for (start = 1; start < end; start++) {
if (new Date(groupPositions[start])[getDate]() !== new Date(groupPositions[start - 1])[getDate]()) {
higherRanks[groupPositions[start]] = DAY;
hasCrossedHigherRank = true;
}
}
// If the complete array has crossed midnight, we want to mark the first
// positions also as higher rank
if (hasCrossedHigherRank) {
higherRanks[groupPositions[0]] = DAY;
}
info.higherRanks = higherRanks;
}
// Save the info
groupPositions.info = info;
// Don't show ticks within a gap in the ordinal axis, where the space between
// two points is greater than a portion of the tick pixel interval
if (findHigherRanks && defined(tickPixelIntervalOption)) { // check for squashed ticks
var length = groupPositions.length,
i = length,
itemToRemove,
translated,
translatedArr = [],
lastTranslated,
medianDistance,
distance,
distances = [];
// Find median pixel distance in order to keep a reasonably even distance between
// ticks (#748)
while (i--) {
translated = xAxis.translate(groupPositions[i]);
if (lastTranslated) {
distances[i] = lastTranslated - translated;
}
translatedArr[i] = lastTranslated = translated;
}
distances.sort();
medianDistance = distances[mathFloor(distances.length / 2)];
if (medianDistance < tickPixelIntervalOption * 0.6) {
medianDistance = null;
}
// Now loop over again and remove ticks where needed
i = groupPositions[length - 1] > max ? length - 1 : length; // #817
lastTranslated = undefined;
while (i--) {
translated = translatedArr[i];
distance = lastTranslated - translated;
// Remove ticks that are closer than 0.6 times the pixel interval from the one to the right,
// but not if it is close to the median distance (#748).
if (lastTranslated && distance < tickPixelIntervalOption * 0.8 &&
(medianDistance === null || distance < medianDistance * 0.8)) {
// Is this a higher ranked position with a normal position to the right?
if (higherRanks[groupPositions[i]] && !higherRanks[groupPositions[i + 1]]) {
// Yes: remove the lower ranked neighbour to the right
itemToRemove = i + 1;
lastTranslated = translated; // #709
} else {
// No: remove this one
itemToRemove = i;
}
groupPositions.splice(itemToRemove, 1);
} else {
lastTranslated = translated;
}
}
}
return groupPositions;
};
/**
* Overrride the chart.pan method for ordinal axes.
*/
var baseChartPan = chart.pan;
chart.pan = function (e) {
var xAxis = chart.xAxis[0],
chartX = e.chartX,
runBase = false;
if (xAxis.options.ordinal && xAxis.series.length) {
var mouseDownX = chart.mouseDownX,
extremes = xAxis.getExtremes(),
dataMax = extremes.dataMax,
min = extremes.min,
max = extremes.max,
trimmedRange,
hoverPoints = chart.hoverPoints,
closestPointRange = xAxis.closestPointRange,
pointPixelWidth = xAxis.translationSlope * (xAxis.ordinalSlope || closestPointRange),
movedUnits = (mouseDownX - chartX) / pointPixelWidth, // how many ordinal units did we move?
extendedAxis = { ordinalPositions: xAxis.getExtendedPositions() }, // get index of all the chart's points
ordinalPositions,
searchAxisLeft,
lin2val = xAxis.lin2val,
val2lin = xAxis.val2lin,
searchAxisRight;
if (!extendedAxis.ordinalPositions) { // we have an ordinal axis, but the data is equally spaced
runBase = true;
} else if (mathAbs(movedUnits) > 1) {
// Remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
if (movedUnits < 0) {
searchAxisLeft = extendedAxis;
searchAxisRight = xAxis.ordinalPositions ? xAxis : extendedAxis;
} else {
searchAxisLeft = xAxis.ordinalPositions ? xAxis : extendedAxis;
searchAxisRight = extendedAxis;
}
// In grouped data series, the last ordinal position represents the grouped data, which is
// to the left of the real data max. If we don't compensate for this, we will be allowed
// to pan grouped data series passed the right of the plot area.
ordinalPositions = searchAxisRight.ordinalPositions;
if (dataMax > ordinalPositions[ordinalPositions.length - 1]) {
ordinalPositions.push(dataMax);
}
// Get the new min and max values by getting the ordinal index for the current extreme,
// then add the moved units and translate back to values. This happens on the
// extended ordinal positions if the new position is out of range, else it happens
// on the current x axis which is smaller and faster.
trimmedRange = xAxis.toFixedRange(null, null,
lin2val.apply(searchAxisLeft, [
val2lin.apply(searchAxisLeft, [min, true]) + movedUnits, // the new index
true // translate from index
]),
lin2val.apply(searchAxisRight, [
val2lin.apply(searchAxisRight, [max, true]) + movedUnits, // the new index
true // translate from index
])
);
// Apply it if it is within the available data range
if (trimmedRange.min >= mathMin(extremes.dataMin, min) && trimmedRange.max <= mathMax(dataMax, max)) {
xAxis.setExtremes(trimmedRange.min, trimmedRange.max, true, false, { trigger: 'pan' });
}
chart.mouseDownX = chartX; // set new reference for next run
css(chart.container, { cursor: 'move' });
}
} else {
runBase = true;
}
// revert to the linear chart.pan version
if (runBase) {
baseChartPan.apply(chart, arguments);
}
};
}
};
/**
* Extend getSegments by identifying gaps in the ordinal data so that we can draw a gap in the
* line or area
*/
seriesProto.getSegments = function () {
var series = this,
segments,
gapSize = series.options.gapSize,
xAxis = series.xAxis;
// call base method
baseGetSegments.apply(series);
if (xAxis.options.ordinal && gapSize) { // #1794
// properties
segments = series.segments;
// extension for ordinal breaks
each(segments, function (segment, no) {
var i = segment.length - 1;
while (i--) {
if (segment[i + 1].x - segment[i].x > xAxis.closestPointRange * gapSize) {
segments.splice( // insert after this one
no + 1,
0,
segment.splice(i + 1, segment.length - i)
);
}
}
});
}
};
}());
/* ****************************************************************************
* End ordinal axis logic *
*****************************************************************************/
// global variables
extend(Highcharts, {
// Constructors
Axis: Axis,
Chart: Chart,
Color: Color,
Legend: Legend,
Pointer: Pointer,
Point: Point,
Tick: Tick,
Tooltip: Tooltip,
Renderer: Renderer,
Series: Series,
SVGElement: SVGElement,
SVGRenderer: SVGRenderer,
// Various
arrayMin: arrayMin,
arrayMax: arrayMax,
charts: charts,
dateFormat: dateFormat,
format: format,
pathAnim: pathAnim,
getOptions: getOptions,
hasBidiBug: hasBidiBug,
isTouchDevice: isTouchDevice,
numberFormat: numberFormat,
seriesTypes: seriesTypes,
setOptions: setOptions,
addEvent: addEvent,
removeEvent: removeEvent,
createElement: createElement,
discardElement: discardElement,
css: css,
each: each,
extend: extend,
map: map,
merge: merge,
pick: pick,
splat: splat,
extendClass: extendClass,
pInt: pInt,
wrap: wrap,
svg: hasSVG,
canvas: useCanVG,
vml: !hasSVG && !useCanVG,
product: PRODUCT,
version: VERSION
});
}());
|
src/js/components/icons/base/Cloud.js | odedre/grommet-final | /**
* @description Cloud SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M18,17 L18,18 C18,21 16,22 13,22 L11,22 C8,22 6,21 6,18 L6,17 C3.23857625,17 1,14.7614237 1,12 C1,9.23857625 3.23857625,7 6,7 L12,7 M6,7 L6,6 C6,3 8,2 11,2 L13,2 C16,2 18,3 18,6 L18,7 C20.7614237,7 23,9.23857625 23,12 C23,14.7614237 20.7614237,17 18,17 L12,17"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-cloud`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'cloud');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M18,17 L18,18 C18,21 16,22 13,22 L11,22 C8,22 6,21 6,18 L6,17 C3.23857625,17 1,14.7614237 1,12 C1,9.23857625 3.23857625,7 6,7 L12,7 M6,7 L6,6 C6,3 8,2 11,2 L13,2 C16,2 18,3 18,6 L18,7 C20.7614237,7 23,9.23857625 23,12 C23,14.7614237 20.7614237,17 18,17 L12,17"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Cloud';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
ajax/libs/rxjs/2.2.10/rx.lite.compat.js | paleozogt/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = { Internals: {} };
// Defaults
function noop() { }
function identity(x) { return x; }
var defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }());
function defaultComparer(x, y) { return isEqual(x, y); }
function defaultSubComparer(x, y) { return x - y; }
function defaultKeySerializer(x) { return x.toString(); }
function defaultError(err) { throw err; }
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() {
if (this.isDisposed) {
throw new Error(objectDisposed);
}
}
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.Internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
var result;
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor,
ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB && !(
isFunction(ctorA) && ctorA instanceof ctorA &&
isFunction(ctorB) && ctorB instanceof ctorB
)) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
length = a.length;
size = b.length;
// compare lengths to determine if a deep comparison is necessary
result = size == a.length;
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
return result;
}
// deep compare each object
for(var key in b) {
if (hasOwnProperty.call(b, key)) {
// count properties and deep compare each property value
size++;
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB));
}
}
if (result) {
// ensure both objects have the same number of properties
for (var key in a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.Internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.Internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.Internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var BooleanDisposable = (function () {
function BooleanDisposable (isSingle) {
this.isSingle = isSingle;
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
if (this.current && this.isSingle) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
inherits(SingleAssignmentDisposable, super_);
function SingleAssignmentDisposable() {
super_.call(this, true);
}
return SingleAssignmentDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
var SerialDisposable = Rx.SerialDisposable = (function (super_) {
inherits(SerialDisposable, super_);
function SerialDisposable() {
super_.call(this, false);
}
return SerialDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.Internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function Trampoline() {
queue = new PriorityQueue(4);
}
Trampoline.prototype.dispose = function () {
queue = null;
};
Trampoline.prototype.run = function () {
var item;
while (queue.length > 0) {
item = queue.dequeue();
if (!item.isCancelled()) {
while (item.dueTime - Scheduler.now() > 0) { }
if (!item.isCancelled()) {
item.invoke();
}
}
}
};
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + normalizeTime(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
t = new Trampoline();
try {
queue.enqueue(si);
t.run();
} catch (e) {
throw e;
} finally {
t.dispose();
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.Internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
var scheduleMethod, clearMethod = noop;
(function () {
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Check for setImmediate first for Node v0.11+
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* @constructor
* @private
*/
var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent) {
this.moveNext = moveNext;
this.getCurrent = getCurrent;
};
/**
* @static
* @memberOf Enumerator
* @private
*/
var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent) {
var done = false;
return new Enumerator(function () {
if (done) {
return false;
}
var result = moveNext();
if (!result) {
done = true;
}
return result;
}, function () { return getCurrent(); });
};
var Enumerable = Rx.Internals.Enumerable = function (getEnumerator) {
this.getEnumerator = getEnumerator;
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, hasNext;
if (isDisposed) { return; }
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
}
} catch (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
observer.onCompleted();
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e = sources.getEnumerator(), isDisposed, lastException;
var subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, hasNext;
if (isDisposed) { return; }
try {
hasNext = e.moveNext();
if (hasNext) {
current = e.getCurrent();
}
} catch (ex) {
observer.onError(ex);
return;
}
if (!hasNext) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (arguments.length === 1) {
repeatCount = -1;
}
return new Enumerable(function () {
var current, left = repeatCount;
return enumeratorCreate(function () {
if (left === 0) {
return false;
}
if (left > 0) {
left--;
}
current = value;
return true;
}, function () { return current; });
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var current, index = -1;
return enumeratorCreate(
function () {
if (++index < source.length) {
current = selector.call(thisArg, source[index], index, source);
return true;
}
return false;
},
function () { return current; }
);
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
*
* @constructor
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
*
* @memberOf AnonymousObserver
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
*
* @memberOf AnonymousObserver
* @param {Any{ error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*
* @memberOf AnonymousObserver
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
/**
* @constructor
* @private
*/
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber;
if (typeof observerOrOnNext === 'object') {
subscriber = observerOrOnNext;
} else {
subscriber = observerCreate(observerOrOnNext, onError, onCompleted);
}
return this._subscribe(subscriber);
};
/**
* Creates a list from an observable sequence.
*
* @memberOf Observable
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
function accumulator(list, i) {
var newList = list.slice(0);
newList.push(i);
return newList;
}
return this.scan([], accumulator).startWith([]).finalValue();
};
return Observable;
})();
/** @private */
var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
/** @private */
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
/** @private */
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
/** @private */
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
/** @private */
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
/** @private */
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == null) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throwException(new Error('Error'));
* var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
if (typeof handlerOrSecond === 'function') {
return observableCatchHandler(this, handlerOrSecond);
}
return observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(args[i].subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) {
observer.onCompleted();
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
if (isOpen) {
observer.onNext(left);
}
}, observer.onError.bind(observer), function () {
if (isOpen) {
observer.onCompleted();
}
}));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
var next = function (i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.doAction(observer);
* var res = observable.doAction(onNext);
* var res = observable.doAction(onNext, onError);
* var res = observable.doAction(onNext, onError, onCompleted);
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = source.subscribe(observer);
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(42);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* var res = source.takeLast(5);
* var res = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
function selectMany(selector) {
return this.select(selector).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x) {
return selector(x).select(function (y) {
return resultSelector(x, y);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = timeoutScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = timeoutScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
function fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = window.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation){
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch(event.type){
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Node.js specific
if (element.addListener) {
element.addListener(name, handler);
return disposableCreate(function () {
element.removeListener(name, handler);
});
}
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
} else if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
} else {
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (el && el.length) {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el[i], eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} A Promises A+ implementation instance.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
});
};
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return !selector ?
this.multicast(new Subject()) :
this.multicast(function () {
return new Subject();
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.share();
*
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish(null).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return !selector ?
this.multicast(new AsyncSubject()) :
this.multicast(function () {
return new AsyncSubject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareValue(42);
*
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).
refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return !selector ?
this.multicast(new ReplaySubject(bufferSize, window, scheduler)) :
this.multicast(function () {
return new ReplaySubject(bufferSize, window, scheduler);
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
/** @private */
var ConnectableObservable = Rx.ConnectableObservable = (function (_super) {
inherits(ConnectableObservable, _super);
/**
* @constructor
* @private
*/
function ConnectableObservable(source, subject) {
var state = {
subject: subject,
source: source.asObservable(),
hasSubscription: false,
subscription: null
};
this.connect = function () {
if (!state.hasSubscription) {
state.hasSubscription = true;
state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () {
state.hasSubscription = false;
}));
}
return state.subscription;
};
function subscribe(observer) {
return state.subject.subscribe(observer);
}
_super.call(this, subscribe);
}
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.connect = function () { return this.connect(); };
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription = null, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect, subscription;
count++;
shouldConnect = count === 1;
subscription = source.subscribe(observer);
if (shouldConnect) {
connectableSubscription = source.connect();
}
return disposableCreate(function () {
subscription.dispose();
count--;
if (count === 0) {
connectableSubscription.dispose();
}
});
});
};
return ConnectableObservable;
}(Observable));
function observableTimerTimeSpan(dueTime, scheduler) {
var d = normalizeTime(dueTime);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(d, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
if (dueTime === period) {
return new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
});
}
return observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return observableTimerTimeSpanAndPeriod(period, period, scheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
*
* @example
* var res = Rx.Observable.timer(5000);
* var res = Rx.Observable.timer(5000, 1000);
* var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
scheduler || (scheduler = timeoutScheduler);
if (typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) {
scheduler = periodOrScheduler;
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* var res = Rx.Observable.delay(5000);
* var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.select(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return {
value: x,
interval: span
};
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.select(function (x) {
return {
value: x,
timestamp: scheduler.now()
};
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
if (atEnd) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
scheduler || (scheduler = timeoutScheduler);
if (typeof intervalOrSampler === 'number') {
return sampleObservable(this, observableinterval(intervalOrSampler, scheduler));
}
return sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
*
* @example
* 1 - res = source.timeout(new Date()); // As a date
* 2 - res = source.timeout(5000); // 5 seconds
* 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable
* 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable
* 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable
* 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
var schedulerMethod, source = this;
other || (other = observableThrow(new Error('Timeout')));
scheduler || (scheduler = timeoutScheduler);
if (dueTime instanceof Date) {
schedulerMethod = function (dt, action) {
scheduler.scheduleWithAbsolute(dt, action);
};
} else {
schedulerMethod = function (dt, action) {
scheduler.scheduleWithRelative(dt, action);
};
}
return new AnonymousObservable(function (observer) {
var createTimer,
id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
createTimer = function () {
var myId = id;
timer.setDisposable(schedulerMethod(dueTime, function () {
switched = id === myId;
var timerWins = switched;
if (timerWins) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
var onNextWins = !switched;
if (onNextWins) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
var onErrorWins = !switched;
if (onErrorWins) {
id++;
observer.onError(e);
}
}, function () {
var onCompletedWins = !switched;
if (onCompletedWins) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
if (hasResult) {
observer.onNext(result);
}
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); });
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
*
* @example
* 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500));
* 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); });
* 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42));
*
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
var firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false, setTimer = function (timeout) {
var myId = id, timerWins = function () {
return id === myId;
};
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
d.dispose();
}, function (e) {
if (timerWins()) {
observer.onError(e);
}
}, function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
setTimer(firstTimeout);
var observerWins = function () {
var res = !switched;
if (res) {
id++;
}
return res;
};
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(timeout);
}
}, function (e) {
if (observerWins()) {
observer.onError(e);
}
}, function () {
if (observerWins()) {
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); });
*
* @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttleWithSelector = function (throttleDurationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
if (hasValue) {
observer.onNext(value);
}
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
*
* @example
* 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) {
return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); });
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
res.push(next.value);
}
}
observer.onNext(res);
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var t = scheduler.scheduleWithRelative(duration, function () {
observer.onCompleted();
});
return new CompositeDisposable(t, source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false,
t = scheduler.scheduleWithRelative(duration, function () { open = true; }),
d = source.subscribe(function (x) {
if (open) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
return new CompositeDisposable(t, d);
});
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]);
* @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var open = false,
t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }),
d = source.subscribe(function (x) {
if (open) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
return new CompositeDisposable(t, d);
});
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]);
* @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} scheduler Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () {
observer.onCompleted();
}), source.subscribe(observer));
});
};
var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) {
inherits(AnonymousObservable, _super);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (typeof subscriber === 'undefined') {
subscriber = disposableEmpty;
} else if (typeof subscriber === 'function') {
subscriber = disposableCreate(subscriber);
}
return subscriber;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
_super.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
var v = this.value;
var hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, _super);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
_super.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (_super) {
function RemovableDisposable (subject, observer) {
this.subject = subject;
this.observer = observer;
};
RemovableDisposable.prototype.dispose = function () {
this.observer.dispose();
if (!this.subject.isDisposed) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
}
};
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = new RemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, _super);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
_super.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/* @private */
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
ajax/libs/graphiql/0.11.3/graphiql.min.js | tholu/cdnjs | !function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).GraphiQL=f()}}(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&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||e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DocExplorer=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&(e[r]=a[r])}return e},_createClass=function(){function e(e,t){for(var a=0;a<t.length;a++){var r=t[a];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,a,r){return a&&e(t.prototype,a),r&&e(t,r),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_graphql=require("graphql"),_FieldDoc2=_interopRequireDefault(require("./DocExplorer/FieldDoc")),_SchemaDoc2=_interopRequireDefault(require("./DocExplorer/SchemaDoc")),_SearchBox2=_interopRequireDefault(require("./DocExplorer/SearchBox")),_SearchResults2=_interopRequireDefault(require("./DocExplorer/SearchResults")),_TypeDoc2=_interopRequireDefault(require("./DocExplorer/TypeDoc")),initialNav={name:"Schema",title:"Documentation Explorer"};(exports.DocExplorer=function(e){function t(){_classCallCheck(this,t);var e=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return e.handleNavBackClick=function(){e.state.navStack.length>1&&e.setState({navStack:e.state.navStack.slice(0,-1)})},e.handleClickTypeOrField=function(t){e.showDoc(t)},e.handleSearch=function(t){e.showSearch(t)},e.state={navStack:[initialNav]},e}return _inherits(t,e),_createClass(t,[{key:"shouldComponentUpdate",value:function(e,t){return this.props.schema!==e.schema||this.state.navStack!==t.navStack}},{key:"render",value:function(){var e=this.props.schema,t=this.state.navStack,a=t[t.length-1],r=void 0;r=void 0===e?_react2.default.createElement("div",{className:"spinner-container"},_react2.default.createElement("div",{className:"spinner"})):e?a.search?_react2.default.createElement(_SearchResults2.default,{searchValue:a.search,withinType:a.def,schema:e,onClickType:this.handleClickTypeOrField,onClickField:this.handleClickTypeOrField}):1===t.length?_react2.default.createElement(_SchemaDoc2.default,{schema:e,onClickType:this.handleClickTypeOrField}):(0,_graphql.isType)(a.def)?_react2.default.createElement(_TypeDoc2.default,{schema:e,type:a.def,onClickType:this.handleClickTypeOrField,onClickField:this.handleClickTypeOrField}):_react2.default.createElement(_FieldDoc2.default,{field:a.def,onClickType:this.handleClickTypeOrField}):_react2.default.createElement("div",{className:"error-container"},"No Schema Available");var c=1===t.length||(0,_graphql.isType)(a.def)&&a.def.getFields,l=void 0;return t.length>1&&(l=t[t.length-2].name),_react2.default.createElement("div",{className:"doc-explorer",key:a.name},_react2.default.createElement("div",{className:"doc-explorer-title-bar"},l&&_react2.default.createElement("div",{className:"doc-explorer-back",onClick:this.handleNavBackClick},l),_react2.default.createElement("div",{className:"doc-explorer-title"},a.title||a.name),_react2.default.createElement("div",{className:"doc-explorer-rhs"},this.props.children)),_react2.default.createElement("div",{className:"doc-explorer-contents"},c&&_react2.default.createElement(_SearchBox2.default,{value:a.search,placeholder:"Search "+a.name+"...",onSearch:this.handleSearch}),r))}},{key:"showDoc",value:function(e){var t=this.state.navStack;t[t.length-1].def!==e&&this.setState({navStack:t.concat([{name:e.name,def:e}])})}},{key:"showDocForReference",value:function(e){"Type"===e.kind?this.showDoc(e.type):"Field"===e.kind?this.showDoc(e.field):"Argument"===e.kind&&e.field?this.showDoc(e.field):"EnumValue"===e.kind&&e.type&&this.showDoc(e.type)}},{key:"showSearch",value:function(e){var t=this.state.navStack.slice(),a=t[t.length-1];t[t.length-1]=_extends({},a,{search:e}),this.setState({navStack:t})}},{key:"reset",value:function(){this.setState({navStack:[initialNav]})}}]),t}(_react2.default.Component)).propTypes={schema:_propTypes2.default.instanceOf(_graphql.GraphQLSchema)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./DocExplorer/FieldDoc":3,"./DocExplorer/SchemaDoc":5,"./DocExplorer/SearchBox":6,"./DocExplorer/SearchResults":7,"./DocExplorer/TypeDoc":8,graphql:92,"prop-types":172}],2:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function Argument(e){var a=e.arg,r=e.onClickType,t=e.showDefaultValue;return _react2.default.createElement("span",{className:"arg"},_react2.default.createElement("span",{className:"arg-name"},a.name),": ",_react2.default.createElement(_TypeLink2.default,{type:a.type,onClick:r}),void 0!==a.defaultValue&&!1!==t&&_react2.default.createElement("span",null," = ",_react2.default.createElement("span",{className:"arg-default-value"},(0,_graphql.print)((0,_graphql.astFromValue)(a.defaultValue,a.type)))))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=Argument;var _react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_graphql=require("graphql"),_TypeLink2=_interopRequireDefault(require("./TypeLink"));Argument.propTypes={arg:_propTypes2.default.object.isRequired,onClickType:_propTypes2.default.func.isRequired,showDefaultValue:_propTypes2.default.bool}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./TypeLink":9,graphql:92,"prop-types":172}],3:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_Argument2=_interopRequireDefault(require("./Argument")),_MarkdownContent2=_interopRequireDefault(require("./MarkdownContent")),_TypeLink2=_interopRequireDefault(require("./TypeLink")),FieldDoc=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.field!==e.field}},{key:"render",value:function(){var e=this,t=this.props.field,r=void 0;return t.args&&t.args.length>0&&(r=_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"arguments"),t.args.map(function(t){return _react2.default.createElement("div",{key:t.name,className:"doc-category-item"},_react2.default.createElement("div",null,_react2.default.createElement(_Argument2.default,{arg:t,onClickType:e.props.onClickType})),_react2.default.createElement(_MarkdownContent2.default,{className:"doc-value-description",markdown:t.description}))}))),_react2.default.createElement("div",null,_react2.default.createElement(_MarkdownContent2.default,{className:"doc-type-description",markdown:t.description||"No Description"}),t.deprecationReason&&_react2.default.createElement(_MarkdownContent2.default,{className:"doc-deprecation",markdown:t.deprecationReason}),_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"type"),_react2.default.createElement(_TypeLink2.default,{type:t.type,onClick:this.props.onClickType})),r)}}]),t}(_react2.default.Component);FieldDoc.propTypes={field:_propTypes2.default.object,onClickType:_propTypes2.default.func},exports.default=FieldDoc}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Argument":2,"./MarkdownContent":4,"./TypeLink":9,"prop-types":172}],4:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_marked2=_interopRequireDefault(require("marked")),MarkdownContent=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.markdown!==e.markdown}},{key:"render",value:function(){var e=this.props.markdown;if(!e)return _react2.default.createElement("div",null);var t=(0,_marked2.default)(e,{sanitize:!0});return _react2.default.createElement("div",{className:this.props.className,dangerouslySetInnerHTML:{__html:t}})}}]),t}(_react2.default.Component);MarkdownContent.propTypes={markdown:_propTypes2.default.string,className:_propTypes2.default.string},exports.default=MarkdownContent}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{marked:167,"prop-types":172}],5:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var a=t[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,r,a){return r&&e(t.prototype,r),a&&e(t,a),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_TypeLink2=_interopRequireDefault(require("./TypeLink")),_MarkdownContent2=_interopRequireDefault(require("./MarkdownContent")),SchemaDoc=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.schema!==e.schema}},{key:"render",value:function(){var e=this.props.schema,t=e.getQueryType(),r=e.getMutationType&&e.getMutationType(),a=e.getSubscriptionType&&e.getSubscriptionType();return _react2.default.createElement("div",null,_react2.default.createElement(_MarkdownContent2.default,{className:"doc-type-description",markdown:"A GraphQL schema provides a root type for each kind of operation."}),_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"root types"),_react2.default.createElement("div",{className:"doc-category-item"},_react2.default.createElement("span",{className:"keyword"},"query"),": ",_react2.default.createElement(_TypeLink2.default,{type:t,onClick:this.props.onClickType})),r&&_react2.default.createElement("div",{className:"doc-category-item"},_react2.default.createElement("span",{className:"keyword"},"mutation"),": ",_react2.default.createElement(_TypeLink2.default,{type:r,onClick:this.props.onClickType})),a&&_react2.default.createElement("div",{className:"doc-category-item"},_react2.default.createElement("span",{className:"keyword"},"subscription"),": ",_react2.default.createElement(_TypeLink2.default,{type:a,onClick:this.props.onClickType}))))}}]),t}(_react2.default.Component);SchemaDoc.propTypes={schema:_propTypes2.default.object,onClickType:_propTypes2.default.func},exports.default=SchemaDoc}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./MarkdownContent":4,"./TypeLink":9,"prop-types":172}],6:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_debounce2=_interopRequireDefault(require("../../utility/debounce")),SearchBox=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.handleChange=function(e){var t=e.target.value;r.setState({value:t}),r.debouncedOnSearch(t)},r.handleClear=function(){r.setState({value:""}),r.props.onSearch("")},r.state={value:e.value||""},r.debouncedOnSearch=(0,_debounce2.default)(200,r.props.onSearch),r}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){return _react2.default.createElement("label",{className:"search-box"},_react2.default.createElement("input",{value:this.state.value,onChange:this.handleChange,type:"text",placeholder:this.props.placeholder}),this.state.value&&_react2.default.createElement("div",{className:"search-box-clear",onClick:this.handleClear},"✕"))}}]),t}(_react2.default.Component);SearchBox.propTypes={value:_propTypes2.default.string,placeholder:_propTypes2.default.string,onSearch:_propTypes2.default.func},exports.default=SearchBox}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../utility/debounce":25,"prop-types":172}],7:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function isMatch(e,t){try{var r=t.replace(/[^_0-9A-Za-z]/g,function(e){return"\\"+e});return-1!==e.search(new RegExp(r,"i"))}catch(r){return-1!==e.toLowerCase().indexOf(t.toLowerCase())}}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_Argument2=_interopRequireDefault(require("./Argument")),_TypeLink2=_interopRequireDefault(require("./TypeLink")),SearchResults=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.schema!==e.schema||this.props.searchValue!==e.searchValue}},{key:"render",value:function(){var e=this.props.searchValue,t=this.props.withinType,r=this.props.schema,n=this.props.onClickType,a=this.props.onClickField,o=[],l=[],u=[],c=r.getTypeMap(),i=Object.keys(c);t&&(i=i.filter(function(e){return e!==t.name})).unshift(t.name);var s=!0,p=!1,f=void 0;try{for(var h,_=i[Symbol.iterator]();!(s=(h=_.next()).done)&&"break"!==function(){var r=h.value;if(o.length+l.length+u.length>=100)return"break";var i=c[r];if(t!==i&&isMatch(r,e)&&l.push(_react2.default.createElement("div",{className:"doc-category-item",key:r},_react2.default.createElement(_TypeLink2.default,{type:i,onClick:n}))),i.getFields){var s=i.getFields();Object.keys(s).forEach(function(l){var c=s[l],p=void 0;if(!isMatch(l,e)){if(!c.args||!c.args.length)return;if(0===(p=c.args.filter(function(t){return isMatch(t.name,e)})).length)return}var f=_react2.default.createElement("div",{className:"doc-category-item",key:r+"."+l},t!==i&&[_react2.default.createElement(_TypeLink2.default,{key:"type",type:i,onClick:n}),"."],_react2.default.createElement("a",{className:"field-name",onClick:function(e){return a(c,i,e)}},c.name),p&&["(",_react2.default.createElement("span",{key:"args"},p.map(function(e){return _react2.default.createElement(_Argument2.default,{key:e.name,arg:e,onClickType:n,showDefaultValue:!1})})),")"]);t===i?o.push(f):u.push(f)})}}();s=!0);}catch(e){p=!0,f=e}finally{try{!s&&_.return&&_.return()}finally{if(p)throw f}}return o.length+l.length+u.length===0?_react2.default.createElement("span",{className:"doc-alert-text"},"No results found."):t&&l.length+u.length>0?_react2.default.createElement("div",null,o,_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"other results"),l,u)):_react2.default.createElement("div",null,o,l,u)}}]),t}(_react2.default.Component);SearchResults.propTypes={schema:_propTypes2.default.object,withinType:_propTypes2.default.object,searchValue:_propTypes2.default.string,onClickType:_propTypes2.default.func,onClickField:_propTypes2.default.func},exports.default=SearchResults}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Argument":2,"./TypeLink":9,"prop-types":172}],8:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function Field(e){var t=e.type,a=e.field,r=e.onClickType,n=e.onClickField;return _react2.default.createElement("div",{className:"doc-category-item"},_react2.default.createElement("a",{className:"field-name",onClick:function(e){return n(a,t,e)}},a.name),a.args&&a.args.length>0&&["(",_react2.default.createElement("span",{key:"args"},a.args.map(function(e){return _react2.default.createElement(_Argument2.default,{key:e.name,arg:e,onClickType:r})})),")"],": ",_react2.default.createElement(_TypeLink2.default,{type:a.type,onClick:r}),a.description&&_react2.default.createElement("p",{className:"field-short-description"},a.description),a.deprecationReason&&_react2.default.createElement(_MarkdownContent2.default,{className:"doc-deprecation",markdown:a.deprecationReason}))}function EnumValue(e){var t=e.value;return _react2.default.createElement("div",{className:"doc-category-item"},_react2.default.createElement("div",{className:"enum-value"},t.name),_react2.default.createElement(_MarkdownContent2.default,{className:"doc-value-description",markdown:t.description}),t.deprecationReason&&_react2.default.createElement(_MarkdownContent2.default,{className:"doc-deprecation",markdown:t.deprecationReason}))}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var a=0;a<t.length;a++){var r=t[a];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,a,r){return a&&e(t.prototype,a),r&&e(t,r),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_graphql=require("graphql"),_Argument2=_interopRequireDefault(require("./Argument")),_MarkdownContent2=_interopRequireDefault(require("./MarkdownContent")),_TypeLink2=_interopRequireDefault(require("./TypeLink")),TypeDoc=function(e){function t(e){_classCallCheck(this,t);var a=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return a.handleShowDeprecated=function(){return a.setState({showDeprecated:!0})},a.state={showDeprecated:!1},a}return _inherits(t,e),_createClass(t,[{key:"shouldComponentUpdate",value:function(e,t){return this.props.type!==e.type||this.props.schema!==e.schema||this.state.showDeprecated!==t.showDeprecated}},{key:"render",value:function(){var e=this.props.schema,t=this.props.type,a=this.props.onClickType,r=this.props.onClickField,n=void 0,c=void 0;t instanceof _graphql.GraphQLUnionType?(n="possible types",c=e.getPossibleTypes(t)):t instanceof _graphql.GraphQLInterfaceType?(n="implementations",c=e.getPossibleTypes(t)):t instanceof _graphql.GraphQLObjectType&&(n="implements",c=t.getInterfaces());var o=void 0;c&&c.length>0&&(o=_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},n),c.map(function(e){return _react2.default.createElement("div",{key:e.name,className:"doc-category-item"},_react2.default.createElement(_TypeLink2.default,{type:e,onClick:a}))})));var l=void 0,i=void 0;if(t.getFields){var p=t.getFields(),s=Object.keys(p).map(function(e){return p[e]});l=_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"fields"),s.filter(function(e){return!e.isDeprecated}).map(function(e){return _react2.default.createElement(Field,{key:e.name,type:t,field:e,onClickType:a,onClickField:r})}));var u=s.filter(function(e){return e.isDeprecated});u.length>0&&(i=_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"deprecated fields"),this.state.showDeprecated?u.map(function(e){return _react2.default.createElement(Field,{key:e.name,type:t,field:e,onClickType:a,onClickField:r})}):_react2.default.createElement("button",{className:"show-btn",onClick:this.handleShowDeprecated},"Show deprecated fields...")))}var d=void 0,f=void 0;if(t instanceof _graphql.GraphQLEnumType){var m=t.getValues();d=_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"values"),m.filter(function(e){return!e.isDeprecated}).map(function(e){return _react2.default.createElement(EnumValue,{key:e.name,value:e})}));var _=m.filter(function(e){return e.isDeprecated});_.length>0&&(f=_react2.default.createElement("div",{className:"doc-category"},_react2.default.createElement("div",{className:"doc-category-title"},"deprecated values"),this.state.showDeprecated?_.map(function(e){return _react2.default.createElement(EnumValue,{key:e.name,value:e})}):_react2.default.createElement("button",{className:"show-btn",onClick:this.handleShowDeprecated},"Show deprecated values...")))}return _react2.default.createElement("div",null,_react2.default.createElement(_MarkdownContent2.default,{className:"doc-type-description",markdown:t.description||"No Description"}),t instanceof _graphql.GraphQLObjectType&&o,l,i,d,f,!(t instanceof _graphql.GraphQLObjectType)&&o)}}]),t}(_react2.default.Component);TypeDoc.propTypes={schema:_propTypes2.default.instanceOf(_graphql.GraphQLSchema),type:_propTypes2.default.object,onClickType:_propTypes2.default.func,onClickField:_propTypes2.default.func},exports.default=TypeDoc,Field.propTypes={type:_propTypes2.default.object,field:_propTypes2.default.object,onClickType:_propTypes2.default.func,onClickField:_propTypes2.default.func},EnumValue.propTypes={value:_propTypes2.default.object}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./Argument":2,"./MarkdownContent":4,"./TypeLink":9,graphql:92,"prop-types":172}],9:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function renderType(e,t){return e instanceof _graphql.GraphQLNonNull?_react2.default.createElement("span",null,renderType(e.ofType,t),"!"):e instanceof _graphql.GraphQLList?_react2.default.createElement("span",null,"[",renderType(e.ofType,t),"]"):_react2.default.createElement("a",{className:"type-name",onClick:function(r){return t(e,r)}},e.name)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_graphql=require("graphql"),TypeLink=function(e){function t(){return _classCallCheck(this,t),_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return _inherits(t,e),_createClass(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.type!==e.type}},{key:"render",value:function(){return renderType(this.props.type,this.props.onClick)}}]),t}(_react2.default.Component);TypeLink.propTypes={type:_propTypes2.default.object,onClick:_propTypes2.default.func},exports.default=TypeLink}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{graphql:92,"prop-types":172}],10:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ExecuteButton=void 0;var _createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types"));(exports.ExecuteButton=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n._onClick=function(){n.props.isRunning?n.props.onStop():n.props.onRun()},n._onOptionSelected=function(e){n.setState({optionsOpen:!1}),n.props.onRun(e.name&&e.name.value)},n._onOptionsOpen=function(e){var t=!0,o=e.target;n.setState({highlight:null,optionsOpen:!0});var r=function(e){t&&e.target===o?t=!1:(document.removeEventListener("mouseup",r),r=null,o.parentNode.compareDocumentPosition(e.target)&Node.DOCUMENT_POSITION_CONTAINED_BY||n.setState({optionsOpen:!1}))};document.addEventListener("mouseup",r)},n.state={optionsOpen:!1,highlight:null},n}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){var e=this,t=this.props.operations,n=this.state.optionsOpen,o=t&&t.length>1,r=null;if(o&&n){var u=this.state.highlight;r=_react2.default.createElement("ul",{className:"execute-options"},t.map(function(t){return _react2.default.createElement("li",{key:t.name?t.name.value:"*",className:t===u&&"selected",onMouseOver:function(){return e.setState({highlight:t})},onMouseOut:function(){return e.setState({highlight:null})},onMouseUp:function(){return e._onOptionSelected(t)}},t.name?t.name.value:"<Unnamed>")}))}var a=void 0;!this.props.isRunning&&o||(a=this._onClick);var i=void 0;this.props.isRunning||!o||n||(i=this._onOptionsOpen);var s=this.props.isRunning?_react2.default.createElement("path",{d:"M 10 10 L 23 10 L 23 23 L 10 23 z"}):_react2.default.createElement("path",{d:"M 11 9 L 24 16 L 11 23 z"});return _react2.default.createElement("div",{className:"execute-button-wrap"},_react2.default.createElement("button",{type:"button",className:"execute-button",onMouseDown:i,onClick:a,title:"Execute Query (Ctrl-Enter)"},_react2.default.createElement("svg",{width:"34",height:"34"},s)),r)}}]),t}(_react2.default.Component)).propTypes={onRun:_propTypes2.default.func,onStop:_propTypes2.default.func,isRunning:_propTypes2.default.bool,operations:_propTypes2.default.array}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"prop-types":172}],11:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function isPromise(e){return"object"===(void 0===e?"undefined":_typeof(e))&&"function"==typeof e.then}function observableToPromise(e){return isObservable(e)?new Promise(function(t,r){var o=e.subscribe(function(e){t(e),o.unsubscribe()},r,function(){r(new Error("no value resolved"))})}):e}function isObservable(e){return"object"===(void 0===e?"undefined":_typeof(e))&&"function"==typeof e.subscribe}Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphiQL=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},_createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_reactDom2=_interopRequireDefault("undefined"!=typeof window?window.ReactDOM:void 0!==global?global.ReactDOM:null),_graphql=require("graphql"),_ExecuteButton=require("./ExecuteButton"),_ToolbarButton=require("./ToolbarButton"),_ToolbarGroup=require("./ToolbarGroup"),_ToolbarMenu=require("./ToolbarMenu"),_ToolbarSelect=require("./ToolbarSelect"),_QueryEditor=require("./QueryEditor"),_VariableEditor=require("./VariableEditor"),_ResultViewer=require("./ResultViewer"),_DocExplorer=require("./DocExplorer"),_QueryHistory=require("./QueryHistory"),_CodeMirrorSizer2=_interopRequireDefault(require("../utility/CodeMirrorSizer")),_StorageAPI2=_interopRequireDefault(require("../utility/StorageAPI")),_getQueryFacts2=_interopRequireDefault(require("../utility/getQueryFacts")),_getSelectedOperationName2=_interopRequireDefault(require("../utility/getSelectedOperationName")),_debounce2=_interopRequireDefault(require("../utility/debounce")),_find2=_interopRequireDefault(require("../utility/find")),_fillLeafs2=require("../utility/fillLeafs"),_elementPosition=require("../utility/elementPosition"),_introspectionQueries=require("../utility/introspectionQueries"),GraphiQL=exports.GraphiQL=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));if(_initialiseProps.call(r),"function"!=typeof e.fetcher)throw new TypeError("GraphiQL requires a fetcher function.");r._storage=new _StorageAPI2.default(e.storage);var o=void 0!==e.query?e.query:null!==r._storage.get("query")?r._storage.get("query"):void 0!==e.defaultQuery?e.defaultQuery:defaultQuery,n=(0,_getQueryFacts2.default)(e.schema,o),i=void 0!==e.variables?e.variables:r._storage.get("variables"),a=void 0!==e.operationName?e.operationName:(0,_getSelectedOperationName2.default)(null,r._storage.get("operationName"),n&&n.operations);return r.state=_extends({schema:e.schema,query:o,variables:i,operationName:a,response:e.response,editorFlex:Number(r._storage.get("editorFlex"))||1,variableEditorOpen:Boolean(i),variableEditorHeight:Number(r._storage.get("variableEditorHeight"))||200,docExplorerOpen:"true"===r._storage.get("docExplorerOpen")||!1,historyPaneOpen:"true"===r._storage.get("historyPaneOpen")||!1,docExplorerWidth:Number(r._storage.get("docExplorerWidth"))||350,isWaitingForResponse:!1,subscription:null},n),r._editorQueryID=0,"object"===("undefined"==typeof window?"undefined":_typeof(window))&&window.addEventListener("beforeunload",function(){return r.componentWillUnmount()}),r}return _inherits(t,e),_createClass(t,[{key:"componentDidMount",value:function(){void 0===this.state.schema&&this._fetchSchema(),this.codeMirrorSizer=new _CodeMirrorSizer2.default,global.g=this}},{key:"componentWillReceiveProps",value:function(e){var t=this,r=this.state.schema,o=this.state.query,n=this.state.variables,i=this.state.operationName,a=this.state.response;if(void 0!==e.schema&&(r=e.schema),void 0!==e.query&&(o=e.query),void 0!==e.variables&&(n=e.variables),void 0!==e.operationName&&(i=e.operationName),void 0!==e.response&&(a=e.response),r!==this.state.schema||o!==this.state.query||i!==this.state.operationName){var s=this._updateQueryFacts(o,i,this.state.operations,r);void 0!==s&&(i=s.operationName,this.setState(s))}void 0===e.schema&&e.fetcher!==this.props.fetcher&&(r=void 0),this.setState({schema:r,query:o,variables:n,operationName:i,response:a},function(){void 0===t.state.schema&&(t.docExplorerComponent.reset(),t._fetchSchema())})}},{key:"componentDidUpdate",value:function(){this.codeMirrorSizer.updateSizes([this.queryEditorComponent,this.variableEditorComponent,this.resultComponent])}},{key:"componentWillUnmount",value:function(){this._storage.set("query",this.state.query),this._storage.set("variables",this.state.variables),this._storage.set("operationName",this.state.operationName),this._storage.set("editorFlex",this.state.editorFlex),this._storage.set("variableEditorHeight",this.state.variableEditorHeight),this._storage.set("docExplorerWidth",this.state.docExplorerWidth),this._storage.set("docExplorerOpen",this.state.docExplorerOpen),this._storage.set("historyPaneOpen",this.state.historyPaneOpen)}},{key:"render",value:function(){var e=this,r=_react2.default.Children.toArray(this.props.children),o=(0,_find2.default)(r,function(e){return e.type===t.Logo})||_react2.default.createElement(t.Logo,null),n=(0,_find2.default)(r,function(e){return e.type===t.Toolbar})||_react2.default.createElement(t.Toolbar,null,_react2.default.createElement(_ToolbarButton.ToolbarButton,{onClick:this.handlePrettifyQuery,title:"Prettify Query",label:"Prettify"}),_react2.default.createElement(_ToolbarButton.ToolbarButton,{onClick:this.handleToggleHistory,title:"Show History",label:"History"})),i=(0,_find2.default)(r,function(e){return e.type===t.Footer}),a={WebkitFlex:this.state.editorFlex,flex:this.state.editorFlex},s={display:this.state.docExplorerOpen?"block":"none",width:this.state.docExplorerWidth},l="docExplorerWrap"+(this.state.docExplorerWidth<200?" doc-explorer-narrow":""),u={display:this.state.historyPaneOpen?"block":"none",width:"230px",zIndex:"7"},c=this.state.variableEditorOpen,d={height:c?this.state.variableEditorHeight:null};return _react2.default.createElement("div",{className:"graphiql-container"},_react2.default.createElement("div",{className:"historyPaneWrap",style:u},_react2.default.createElement(_QueryHistory.QueryHistory,{operationName:this.state.operationName,query:this.state.query,variables:this.state.variables,onSelectQuery:this.handleSelectHistoryQuery,storage:this._storage,queryID:this._editorQueryID},_react2.default.createElement("div",{className:"docExplorerHide",onClick:this.handleToggleHistory},"✕"))),_react2.default.createElement("div",{className:"editorWrap"},_react2.default.createElement("div",{className:"topBarWrap"},_react2.default.createElement("div",{className:"topBar"},o,_react2.default.createElement(_ExecuteButton.ExecuteButton,{isRunning:Boolean(this.state.subscription),onRun:this.handleRunQuery,onStop:this.handleStopQuery,operations:this.state.operations}),n),!this.state.docExplorerOpen&&_react2.default.createElement("button",{className:"docExplorerShow",onClick:this.handleToggleDocs},"Docs")),_react2.default.createElement("div",{ref:function(t){e.editorBarComponent=t},className:"editorBar",onMouseDown:this.handleResizeStart},_react2.default.createElement("div",{className:"queryWrap",style:a},_react2.default.createElement(_QueryEditor.QueryEditor,{ref:function(t){e.queryEditorComponent=t},schema:this.state.schema,value:this.state.query,onEdit:this.handleEditQuery,onHintInformationRender:this.handleHintInformationRender,onClickReference:this.handleClickReference,onRunQuery:this.handleEditorRunQuery,editorTheme:this.props.editorTheme}),_react2.default.createElement("div",{className:"variable-editor",style:d},_react2.default.createElement("div",{className:"variable-editor-title",style:{cursor:c?"row-resize":"n-resize"},onMouseDown:this.handleVariableResizeStart},"Query Variables"),_react2.default.createElement(_VariableEditor.VariableEditor,{ref:function(t){e.variableEditorComponent=t},value:this.state.variables,variableToType:this.state.variableToType,onEdit:this.handleEditVariables,onHintInformationRender:this.handleHintInformationRender,onRunQuery:this.handleEditorRunQuery,editorTheme:this.props.editorTheme}))),_react2.default.createElement("div",{className:"resultWrap"},this.state.isWaitingForResponse&&_react2.default.createElement("div",{className:"spinner-container"},_react2.default.createElement("div",{className:"spinner"})),_react2.default.createElement(_ResultViewer.ResultViewer,{ref:function(t){e.resultComponent=t},value:this.state.response,editorTheme:this.props.editorTheme}),i))),_react2.default.createElement("div",{className:l,style:s},_react2.default.createElement("div",{className:"docExplorerResizer",onMouseDown:this.handleDocsResizeStart}),_react2.default.createElement(_DocExplorer.DocExplorer,{ref:function(t){e.docExplorerComponent=t},schema:this.state.schema},_react2.default.createElement("div",{className:"docExplorerHide",onClick:this.handleToggleDocs},"✕"))))}},{key:"getQueryEditor",value:function(){return this.queryEditorComponent.getCodeMirror()}},{key:"getVariableEditor",value:function(){return this.variableEditorComponent.getCodeMirror()}},{key:"refresh",value:function(){this.queryEditorComponent.getCodeMirror().refresh(),this.variableEditorComponent.getCodeMirror().refresh(),this.resultComponent.getCodeMirror().refresh()}},{key:"autoCompleteLeafs",value:function(){var e=(0,_fillLeafs2.fillLeafs)(this.state.schema,this.state.query,this.props.getDefaultFieldNames),t=e.insertions,r=e.result;if(t&&t.length>0){var o=this.getQueryEditor();o.operation(function(){var e=o.getCursor(),n=o.indexFromPos(e);o.setValue(r);var i=0,a=t.map(function(e){var t=e.index,r=e.string;return o.markText(o.posFromIndex(t+i),o.posFromIndex(t+(i+=r.length)),{className:"autoInsertedLeaf",clearOnEnter:!0,title:"Automatically added leaf fields"})});setTimeout(function(){return a.forEach(function(e){return e.clear()})},7e3);var s=n;t.forEach(function(e){var t=e.index,r=e.string;t<n&&(s+=r.length)}),o.setCursor(o.posFromIndex(s))})}return r}},{key:"_fetchSchema",value:function(){var e=this,t=this.props.fetcher,r=observableToPromise(t({query:_introspectionQueries.introspectionQuery}));isPromise(r)?r.then(function(e){if(e.data)return e;var o=observableToPromise(t({query:_introspectionQueries.introspectionQuerySansSubscriptions}));if(!isPromise(r))throw new Error("Fetcher did not return a Promise for introspection.");return o}).then(function(t){if(void 0===e.state.schema)if(t&&t.data){var r=(0,_graphql.buildClientSchema)(t.data),o=(0,_getQueryFacts2.default)(r,e.state.query);e.setState(_extends({schema:r},o))}else{var n="string"==typeof t?t:JSON.stringify(t,null,2);e.setState({schema:null,response:n})}}).catch(function(t){e.setState({schema:null,response:t&&String(t.stack||t)})}):this.setState({response:"Fetcher did not return a Promise for introspection."})}},{key:"_fetchQuery",value:function(e,t,r,o){var n=this,i=this.props.fetcher,a=null;try{a=t&&""!==t.trim()?JSON.parse(t):null}catch(e){throw new Error("Variables are invalid JSON: "+e.message+".")}if("object"!==(void 0===a?"undefined":_typeof(a)))throw new Error("Variables are not a JSON object.");var s=i({query:e,variables:a,operationName:r});if(!isPromise(s)){if(isObservable(s))return s.subscribe({next:o,error:function(e){n.setState({isWaitingForResponse:!1,response:e&&String(e.stack||e),subscription:null})},complete:function(){n.setState({isWaitingForResponse:!1,subscription:null})}});throw new Error("Fetcher did not return Promise or Observable.")}s.then(o).catch(function(e){n.setState({isWaitingForResponse:!1,response:e&&String(e.stack||e)})})}},{key:"_runQueryAtCursor",value:function(){if(this.state.subscription)this.handleStopQuery();else{var e=void 0,t=this.state.operations;if(t){var r=this.getQueryEditor();if(r.hasFocus())for(var o=r.getCursor(),n=r.indexFromPos(o),i=0;i<t.length;i++){var a=t[i];if(a.loc.start<=n&&a.loc.end>=n){e=a.name&&a.name.value;break}}}this.handleRunQuery(e)}}},{key:"_didClickDragBar",value:function(e){if(0!==e.button||e.ctrlKey)return!1;var t=e.target;if(0!==t.className.indexOf("CodeMirror-gutter"))return!1;for(var r=_reactDom2.default.findDOMNode(this.resultComponent);t;){if(t===r)return!0;t=t.parentNode}return!1}}]),t}(_react2.default.Component);GraphiQL.propTypes={fetcher:_propTypes2.default.func.isRequired,schema:_propTypes2.default.instanceOf(_graphql.GraphQLSchema),query:_propTypes2.default.string,variables:_propTypes2.default.string,operationName:_propTypes2.default.string,response:_propTypes2.default.string,storage:_propTypes2.default.shape({getItem:_propTypes2.default.func,setItem:_propTypes2.default.func,removeItem:_propTypes2.default.func}),defaultQuery:_propTypes2.default.string,onEditQuery:_propTypes2.default.func,onEditVariables:_propTypes2.default.func,onEditOperationName:_propTypes2.default.func,onToggleDocs:_propTypes2.default.func,getDefaultFieldNames:_propTypes2.default.func,editorTheme:_propTypes2.default.string,onToggleHistory:_propTypes2.default.func};var _initialiseProps=function(){var e=this;this.handleClickReference=function(t){e.setState({docExplorerOpen:!0},function(){e.docExplorerComponent.showDocForReference(t)})},this.handleRunQuery=function(t){var r=++e._editorQueryID,o=e.autoCompleteLeafs()||e.state.query,n=e.state.variables,i=e.state.operationName;t&&t!==i&&(i=t,e.handleEditOperationName(i));try{e.setState({isWaitingForResponse:!0,response:null,operationName:i});var a=e._fetchQuery(o,n,i,function(t){r===e._editorQueryID&&e.setState({isWaitingForResponse:!1,response:JSON.stringify(t,null,2)})});e.setState({subscription:a})}catch(t){e.setState({isWaitingForResponse:!1,response:t.message})}},this.handleStopQuery=function(){var t=e.state.subscription;e.setState({isWaitingForResponse:!1,subscription:null}),t&&t.unsubscribe()},this.handlePrettifyQuery=function(){var t=e.getQueryEditor();t.setValue((0,_graphql.print)((0,_graphql.parse)(t.getValue())))},this.handleEditQuery=(0,_debounce2.default)(100,function(t){var r=e._updateQueryFacts(t,e.state.operationName,e.state.operations,e.state.schema);if(e.setState(_extends({query:t},r)),e.props.onEditQuery)return e.props.onEditQuery(t)}),this._updateQueryFacts=function(t,r,o,n){var i=(0,_getQueryFacts2.default)(n,t);if(i){var a=(0,_getSelectedOperationName2.default)(o,r,i.operations),s=e.props.onEditOperationName;return s&&r!==a&&s(a),_extends({operationName:a},i)}},this.handleEditVariables=function(t){e.setState({variables:t}),e.props.onEditVariables&&e.props.onEditVariables(t)},this.handleEditOperationName=function(t){var r=e.props.onEditOperationName;r&&r(t)},this.handleHintInformationRender=function(t){t.addEventListener("click",e._onClickHintInformation);var r=void 0;t.addEventListener("DOMNodeRemoved",r=function(){t.removeEventListener("DOMNodeRemoved",r),t.removeEventListener("click",e._onClickHintInformation)})},this.handleEditorRunQuery=function(){e._runQueryAtCursor()},this._onClickHintInformation=function(t){if("typeName"===t.target.className){var r=t.target.innerHTML,o=e.state.schema;if(o){var n=o.getType(r);n&&e.setState({docExplorerOpen:!0},function(){e.docExplorerComponent.showDoc(n)})}}},this.handleToggleDocs=function(){"function"==typeof e.props.onToggleDocs&&e.props.onToggleDocs(!e.state.docExplorerOpen),e.setState({docExplorerOpen:!e.state.docExplorerOpen})},this.handleToggleHistory=function(){"function"==typeof e.props.onToggleHistory&&e.props.onToggleHistory(!e.state.historyPaneOpen),e.setState({historyPaneOpen:!e.state.historyPaneOpen})},this.handleSelectHistoryQuery=function(t,r,o){e.handleEditQuery(t),e.handleEditVariables(r),e.handleEditOperationName(o)},this.handleResizeStart=function(t){if(e._didClickDragBar(t)){t.preventDefault();var r=t.clientX-(0,_elementPosition.getLeft)(t.target),o=function(t){if(0===t.buttons)return n();var o=_reactDom2.default.findDOMNode(e.editorBarComponent),i=t.clientX-(0,_elementPosition.getLeft)(o)-r,a=o.clientWidth-i;e.setState({editorFlex:i/a})},n=function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",n),o=null,n=null});document.addEventListener("mousemove",o),document.addEventListener("mouseup",n)}},this.handleDocsResizeStart=function(t){t.preventDefault();var r=e.state.docExplorerWidth,o=t.clientX-(0,_elementPosition.getLeft)(t.target),n=function(t){if(0===t.buttons)return i();var r=_reactDom2.default.findDOMNode(e),n=t.clientX-(0,_elementPosition.getLeft)(r)-o,a=r.clientWidth-n;a<100?e.setState({docExplorerOpen:!1}):e.setState({docExplorerOpen:!0,docExplorerWidth:Math.min(a,650)})},i=function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){e.state.docExplorerOpen||e.setState({docExplorerWidth:r}),document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",i),n=null,i=null});document.addEventListener("mousemove",n),document.addEventListener("mouseup",i)},this.handleVariableResizeStart=function(t){t.preventDefault();var r=!1,o=e.state.variableEditorOpen,n=e.state.variableEditorHeight,i=t.clientY-(0,_elementPosition.getTop)(t.target),a=function(t){if(0===t.buttons)return s();r=!0;var o=_reactDom2.default.findDOMNode(e.editorBarComponent),a=t.clientY-(0,_elementPosition.getTop)(o)-i,l=o.clientHeight-a;l<60?e.setState({variableEditorOpen:!1,variableEditorHeight:n}):e.setState({variableEditorOpen:!0,variableEditorHeight:l})},s=function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){r||e.setState({variableEditorOpen:!o}),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",s),a=null,s=null});document.addEventListener("mousemove",a),document.addEventListener("mouseup",s)}};GraphiQL.Logo=function(e){return _react2.default.createElement("div",{className:"title"},e.children||_react2.default.createElement("span",null,"Graph",_react2.default.createElement("em",null,"i"),"QL"))},GraphiQL.Toolbar=function(e){return _react2.default.createElement("div",{className:"toolbar"},e.children)},GraphiQL.Button=_ToolbarButton.ToolbarButton,GraphiQL.ToolbarButton=_ToolbarButton.ToolbarButton,GraphiQL.Group=_ToolbarGroup.ToolbarGroup,GraphiQL.Menu=_ToolbarMenu.ToolbarMenu,GraphiQL.MenuItem=_ToolbarMenu.ToolbarMenuItem,GraphiQL.Select=_ToolbarSelect.ToolbarSelect,GraphiQL.SelectOption=_ToolbarSelect.ToolbarSelectOption,GraphiQL.Footer=function(e){return _react2.default.createElement("div",{className:"footer"},e.children)};var defaultQuery='# Welcome to GraphiQL\n#\n# GraphiQL is an in-browser tool for writing, validating, and\n# testing GraphQL queries.\n#\n# Type queries into this side of the screen, and you will see intelligent\n# typeaheads aware of the current GraphQL type schema and live syntax and\n# validation errors highlighted within the text.\n#\n# GraphQL queries typically start with a "{" character. Lines that starts\n# with a # are ignored.\n#\n# An example GraphQL query might look like:\n#\n# {\n# field(arg: "value") {\n# subField\n# }\n# }\n#\n# Keyboard shortcuts:\n#\n# Run Query: Ctrl-Enter (or press the play button above)\n#\n# Auto Complete: Ctrl-Space (or just start typing)\n#\n\n'}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utility/CodeMirrorSizer":22,"../utility/StorageAPI":24,"../utility/debounce":25,"../utility/elementPosition":26,"../utility/fillLeafs":27,"../utility/find":28,"../utility/getQueryFacts":29,"../utility/getSelectedOperationName":30,"../utility/introspectionQueries":31,"./DocExplorer":1,"./ExecuteButton":10,"./QueryEditor":13,"./QueryHistory":14,"./ResultViewer":15,"./ToolbarButton":16,"./ToolbarGroup":17,"./ToolbarMenu":18,"./ToolbarSelect":19,"./VariableEditor":20,graphql:92,"prop-types":172}],12:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,r,i){return r&&e(t.prototype,r),i&&e(t,i),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),HistoryQuery=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e)),i=r.props.favorite?"visible":"hidden";return r.state={starVisibility:i},r}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){this.props.favorite&&"hidden"===this.state.starVisibility&&this.setState({starVisibility:"visible"});var e={float:"right",visibility:this.state.starVisibility},t=this.props.operationName||this.props.query.split("\n").filter(function(e){return 0!==e.indexOf("#")}).join(""),r=this.props.favorite?"★":"☆";return _react2.default.createElement("p",{onClick:this.handleClick.bind(this),onMouseEnter:this.handleMouseEnter.bind(this),onMouseLeave:this.handleMouseLeave.bind(this)},_react2.default.createElement("span",null,t),_react2.default.createElement("span",{onClick:this.handleStarClick.bind(this),style:e},r))}},{key:"handleMouseEnter",value:function(){this.props.favorite||this.setState({starVisibility:"visible"})}},{key:"handleMouseLeave",value:function(){this.props.favorite||this.setState({starVisibility:"hidden"})}},{key:"handleClick",value:function(){this.props.onSelect(this.props.query,this.props.variables,this.props.operationName)}},{key:"handleStarClick",value:function(e){e.stopPropagation(),this.props.handleToggleFavorite(this.props.query,this.props.variables,this.props.operationName,this.props.favorite)}}]),t}(_react2.default.Component);HistoryQuery.propTypes={favorite:_propTypes2.default.bool,favoriteSize:_propTypes2.default.number,handleToggleFavorite:_propTypes2.default.func,operationName:_propTypes2.default.string,onSelect:_propTypes2.default.func,query:_propTypes2.default.string,variables:_propTypes2.default.string},exports.default=HistoryQuery}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"prop-types":172}],13:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,r){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!r||"object"!=typeof r&&"function"!=typeof r?e:r}function _inherits(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function, not "+typeof r);e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),r&&(Object.setPrototypeOf?Object.setPrototypeOf(e,r):e.__proto__=r)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.QueryEditor=void 0;var _createClass=function(){function e(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(r,t,o){return t&&e(r.prototype,t),o&&e(r,o),r}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_graphql=require("graphql"),_marked2=_interopRequireDefault(require("marked")),_normalizeWhitespace=require("../utility/normalizeWhitespace"),_onHasCompletion2=_interopRequireDefault(require("../utility/onHasCompletion")),AUTO_COMPLETE_AFTER_KEY=/^[a-zA-Z0-9_@(]$/;(exports.QueryEditor=function(e){function r(e){_classCallCheck(this,r);var t=_possibleConstructorReturn(this,(r.__proto__||Object.getPrototypeOf(r)).call(this));return t._onKeyUp=function(e,r){AUTO_COMPLETE_AFTER_KEY.test(r.key)&&t.editor.execCommand("autocomplete")},t._onEdit=function(){t.ignoreChangeEvent||(t.cachedValue=t.editor.getValue(),t.props.onEdit&&t.props.onEdit(t.cachedValue))},t._onHasCompletion=function(e,r){(0,_onHasCompletion2.default)(e,r,t.props.onHintInformationRender)},t.cachedValue=e.value||"",t}return _inherits(r,e),_createClass(r,[{key:"componentDidMount",value:function(){var e=this,r=require("codemirror");require("codemirror/addon/hint/show-hint"),require("codemirror/addon/comment/comment"),require("codemirror/addon/edit/matchbrackets"),require("codemirror/addon/edit/closebrackets"),require("codemirror/addon/fold/foldgutter"),require("codemirror/addon/fold/brace-fold"),require("codemirror/addon/lint/lint"),require("codemirror/keymap/sublime"),require("codemirror-graphql/hint"),require("codemirror-graphql/lint"),require("codemirror-graphql/info"),require("codemirror-graphql/jump"),require("codemirror-graphql/mode"),this.editor=r(this._node,{value:this.props.value||"",lineNumbers:!0,tabSize:2,mode:"graphql",theme:this.props.editorTheme||"graphiql",keyMap:"sublime",autoCloseBrackets:!0,matchBrackets:!0,showCursorWhenSelecting:!0,foldGutter:{minFoldSize:4},lint:{schema:this.props.schema},hintOptions:{schema:this.props.schema,closeOnUnfocus:!1,completeSingle:!1},info:{schema:this.props.schema,renderDescription:function(e){return(0,_marked2.default)(e,{sanitize:!0})},onClick:function(r){return e.props.onClickReference(r)}},jump:{schema:this.props.schema,onClick:function(r){return e.props.onClickReference(r)}},gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"],extraKeys:{"Cmd-Space":function(){return e.editor.showHint({completeSingle:!0})},"Ctrl-Space":function(){return e.editor.showHint({completeSingle:!0})},"Alt-Space":function(){return e.editor.showHint({completeSingle:!0})},"Shift-Space":function(){return e.editor.showHint({completeSingle:!0})},"Cmd-Enter":function(){e.props.onRunQuery&&e.props.onRunQuery()},"Ctrl-Enter":function(){e.props.onRunQuery&&e.props.onRunQuery()},"Ctrl-Left":"goSubwordLeft","Ctrl-Right":"goSubwordRight","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight"}}),this.editor.on("change",this._onEdit),this.editor.on("keyup",this._onKeyUp),this.editor.on("hasCompletion",this._onHasCompletion),this.editor.on("beforeChange",this._onBeforeChange)}},{key:"componentDidUpdate",value:function(e){var r=require("codemirror");this.ignoreChangeEvent=!0,this.props.schema!==e.schema&&(this.editor.options.lint.schema=this.props.schema,this.editor.options.hintOptions.schema=this.props.schema,this.editor.options.info.schema=this.props.schema,this.editor.options.jump.schema=this.props.schema,r.signal(this.editor,"change",this.editor)),this.props.value!==e.value&&this.props.value!==this.cachedValue&&(this.cachedValue=this.props.value,this.editor.setValue(this.props.value)),this.ignoreChangeEvent=!1}},{key:"componentWillUnmount",value:function(){this.editor.off("change",this._onEdit),this.editor.off("keyup",this._onKeyUp),this.editor.off("hasCompletion",this._onHasCompletion),this.editor=null}},{key:"render",value:function(){var e=this;return _react2.default.createElement("div",{className:"query-editor",ref:function(r){e._node=r}})}},{key:"getCodeMirror",value:function(){return this.editor}},{key:"getClientHeight",value:function(){return this._node&&this._node.clientHeight}},{key:"_onBeforeChange",value:function(e,r){if("paste"===r.origin){var t=r.text.map(_normalizeWhitespace.normalizeWhitespace);r.update(r.from,r.to,t)}}}]),r}(_react2.default.Component)).propTypes={schema:_propTypes2.default.instanceOf(_graphql.GraphQLSchema),value:_propTypes2.default.string,onEdit:_propTypes2.default.func,onHintInformationRender:_propTypes2.default.func,onClickReference:_propTypes2.default.func,onRunQuery:_propTypes2.default.func,editorTheme:_propTypes2.default.string}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utility/normalizeWhitespace":32,"../utility/onHasCompletion":33,codemirror:63,"codemirror-graphql/hint":35,"codemirror-graphql/info":36,"codemirror-graphql/jump":37,"codemirror-graphql/lint":38,"codemirror-graphql/mode":39,"codemirror/addon/comment/comment":51,"codemirror/addon/edit/closebrackets":53,"codemirror/addon/edit/matchbrackets":54,"codemirror/addon/fold/brace-fold":55,"codemirror/addon/fold/foldgutter":57,"codemirror/addon/hint/show-hint":58,"codemirror/addon/lint/lint":59,"codemirror/keymap/sublime":62,graphql:92,marked:167,"prop-types":172}],14:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.QueryHistory=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},_createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_graphql=require("graphql"),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_QueryStore2=_interopRequireDefault(require("../utility/QueryStore")),_HistoryQuery2=_interopRequireDefault(require("./HistoryQuery")),shouldSaveQuery=function(e,t,r){if(e.queryID===t.queryID)return!1;try{(0,_graphql.parse)(e.query)}catch(e){return!1}if(!r)return!0;if(JSON.stringify(e.query)===JSON.stringify(r.query)){if(JSON.stringify(e.variables)===JSON.stringify(r.variables))return!1;if(!e.variables&&!r.variables)return!1}return!0};(exports.QueryHistory=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));_initialiseProps.call(r),r.historyStore=new _QueryStore2.default("queries",e.storage),r.favoriteStore=new _QueryStore2.default("favorites",e.storage);var o=r.historyStore.fetchAll(),i=r.favoriteStore.fetchAll(),a=o.concat(i);return r.state={queries:a},r}return _inherits(t,e),_createClass(t,[{key:"componentWillReceiveProps",value:function(e){if(shouldSaveQuery(e,this.props,this.historyStore.fetchRecent())){var t={query:e.query,variables:e.variables,operationName:e.operationName};this.historyStore.push(t),this.historyStore.length>20&&this.historyStore.shift();var r=this.historyStore.items,o=this.favoriteStore.items,i=r.concat(o);this.setState({queries:i})}}},{key:"render",value:function(){var e=this,t=this.state.queries.slice().reverse().map(function(t,r){return _react2.default.createElement(_HistoryQuery2.default,_extends({handleToggleFavorite:e.toggleFavorite,key:r,onSelect:e.props.onSelectQuery},t))});return _react2.default.createElement("div",null,_react2.default.createElement("div",{className:"history-title-bar"},_react2.default.createElement("div",{className:"history-title"},"History"),_react2.default.createElement("div",{className:"doc-explorer-rhs"},this.props.children)),_react2.default.createElement("div",{className:"history-contents"},t))}}]),t}(_react2.default.Component)).propTypes={query:_propTypes2.default.string,variables:_propTypes2.default.string,operationName:_propTypes2.default.string,queryID:_propTypes2.default.number,onSelectQuery:_propTypes2.default.func,storage:_propTypes2.default.object};var _initialiseProps=function(){var e=this;this.toggleFavorite=function(t,r,o,i){var a={query:t,variables:r,operationName:o};e.favoriteStore.contains(a)?i&&(a.favorite=!1,e.favoriteStore.delete(a)):(a.favorite=!0,e.favoriteStore.push(a));var s=e.historyStore.items,n=e.favoriteStore.items,u=s.concat(n);e.setState({queries:u})}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utility/QueryStore":23,"./HistoryQuery":12,graphql:92,"prop-types":172}],15:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,r){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!r||"object"!=typeof r&&"function"!=typeof r?e:r}function _inherits(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function, not "+typeof r);e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),r&&(Object.setPrototypeOf?Object.setPrototypeOf(e,r):e.__proto__=r)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResultViewer=void 0;var _createClass=function(){function e(e,r){for(var t=0;t<r.length;t++){var o=r[t];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(r,t,o){return t&&e(r.prototype,t),o&&e(r,o),r}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types"));(exports.ResultViewer=function(e){function r(){return _classCallCheck(this,r),_possibleConstructorReturn(this,(r.__proto__||Object.getPrototypeOf(r)).apply(this,arguments))}return _inherits(r,e),_createClass(r,[{key:"componentDidMount",value:function(){var e=require("codemirror");require("codemirror/addon/fold/foldgutter"),require("codemirror/addon/fold/brace-fold"),require("codemirror/addon/dialog/dialog"),require("codemirror/addon/search/search"),require("codemirror/keymap/sublime"),require("codemirror-graphql/results/mode"),this.viewer=e(this._node,{lineWrapping:!0,value:this.props.value||"",readOnly:!0,theme:this.props.editorTheme||"graphiql",mode:"graphql-results",keyMap:"sublime",foldGutter:{minFoldSize:4},gutters:["CodeMirror-foldgutter"],extraKeys:{"Ctrl-Left":"goSubwordLeft","Ctrl-Right":"goSubwordRight","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight"}})}},{key:"shouldComponentUpdate",value:function(e){return this.props.value!==e.value}},{key:"componentDidUpdate",value:function(){this.viewer.setValue(this.props.value||"")}},{key:"componentWillUnmount",value:function(){this.viewer=null}},{key:"render",value:function(){var e=this;return _react2.default.createElement("div",{className:"result-window",ref:function(r){e._node=r}})}},{key:"getCodeMirror",value:function(){return this.viewer}},{key:"getClientHeight",value:function(){return this._node&&this._node.clientHeight}}]),r}(_react2.default.Component)).propTypes={value:_propTypes2.default.string,editorTheme:_propTypes2.default.string}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{codemirror:63,"codemirror-graphql/results/mode":40,"codemirror/addon/dialog/dialog":52,"codemirror/addon/fold/brace-fold":55,"codemirror/addon/fold/foldgutter":57,"codemirror/addon/search/search":60,"codemirror/keymap/sublime":62,"prop-types":172}],16:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function preventDefault(e){e.preventDefault()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ToolbarButton=void 0;var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types"));(exports.ToolbarButton=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.handleClick=function(e){e.preventDefault();try{r.props.onClick(),r.setState({error:null})}catch(e){r.setState({error:e})}},r.state={error:null},r}return _inherits(t,e),_createClass(t,[{key:"render",value:function(){var e=this.state.error;return _react2.default.createElement("a",{className:"toolbar-button"+(e?" error":""),onMouseDown:preventDefault,onClick:this.handleClick,title:e?e.message:this.props.title},this.props.label)}}]),t}(_react2.default.Component)).propTypes={onClick:_propTypes2.default.func,title:_propTypes2.default.string,label:_propTypes2.default.string}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"prop-types":172}],17:[function(require,module,exports){(function(global){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ToolbarGroup=function(e){var r=e.children;return _react2.default.createElement("div",{className:"toolbar-button-group"},r)};var _react2=function(e){return e&&e.__esModule?e:{default:e}}("undefined"!=typeof window?window.React:void 0!==global?global.React:null)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],18:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function ToolbarMenuItem(e){var t=e.onSelect,n=e.title,r=e.label;return _react2.default.createElement("li",{onMouseOver:function(e){e.target.className="hover"},onMouseOut:function(e){e.target.className=null},onMouseDown:preventDefault,onMouseUp:t,title:n},r)}function preventDefault(e){e.preventDefault()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ToolbarMenu=void 0;var _createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();exports.ToolbarMenuItem=ToolbarMenuItem;var _react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types"));(exports.ToolbarMenu=function(e){function t(e){_classCallCheck(this,t);var n=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.handleOpen=function(e){preventDefault(e),n.setState({visible:!0}),n._subscribe()},n.state={visible:!1},n}return _inherits(t,e),_createClass(t,[{key:"componentWillUnmount",value:function(){this._release()}},{key:"render",value:function(){var e=this,t=this.state.visible;return _react2.default.createElement("a",{className:"toolbar-menu toolbar-button",onClick:this.handleOpen.bind(this),onMouseDown:preventDefault,ref:function(t){e._node=t},title:this.props.title},this.props.label,_react2.default.createElement("svg",{width:"14",height:"8"},_react2.default.createElement("path",{fill:"#666",d:"M 5 1.5 L 14 1.5 L 9.5 7 z"})),_react2.default.createElement("ul",{className:"toolbar-menu-items"+(t?" open":"")},this.props.children))}},{key:"_subscribe",value:function(){this._listener||(this._listener=this.handleClick.bind(this),document.addEventListener("click",this._listener))}},{key:"_release",value:function(){this._listener&&(document.removeEventListener("click",this._listener),this._listener=null)}},{key:"handleClick",value:function(e){this._node!==e.target&&(preventDefault(e),this.setState({visible:!1}),this._release())}}]),t}(_react2.default.Component)).propTypes={title:_propTypes2.default.string,label:_propTypes2.default.string},ToolbarMenuItem.propTypes={onSelect:_propTypes2.default.func,title:_propTypes2.default.string,label:_propTypes2.default.string}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"prop-types":172}],19:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function ToolbarSelectOption(e){var t=e.onSelect,r=e.label,n=e.selected;return _react2.default.createElement("li",{onMouseOver:function(e){e.target.className="hover"},onMouseOut:function(e){e.target.className=null},onMouseDown:preventDefault,onMouseUp:t},r,n&&_react2.default.createElement("svg",{width:"13",height:"13"},_react2.default.createElement("polygon",{points:"4.851,10.462 0,5.611 2.314,3.297 4.851,5.835 10.686,0 13,2.314 4.851,10.462"})))}function preventDefault(e){e.preventDefault()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ToolbarSelect=void 0;var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();exports.ToolbarSelectOption=ToolbarSelectOption;var _react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types"));(exports.ToolbarSelect=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.handleOpen=function(e){preventDefault(e),r.setState({visible:!0}),r._subscribe()},r.state={visible:!1},r}return _inherits(t,e),_createClass(t,[{key:"componentWillUnmount",value:function(){this._release()}},{key:"render",value:function(){var e=this,t=void 0,r=this.state.visible,n=_react2.default.Children.map(this.props.children,function(r,n){t&&!r.props.selected||(t=r);var o=r.props.onSelect||e.props.onSelect&&e.props.onSelect.bind(null,r.props.value,n);return _react2.default.createElement(ToolbarSelectOption,_extends({},r.props,{onSelect:o}))});return _react2.default.createElement("a",{className:"toolbar-select toolbar-button",onClick:this.handleOpen.bind(this),onMouseDown:preventDefault,ref:function(t){e._node=t},title:this.props.title},t.props.label,_react2.default.createElement("svg",{width:"13",height:"10"},_react2.default.createElement("path",{fill:"#666",d:"M 5 5 L 13 5 L 9 1 z"}),_react2.default.createElement("path",{fill:"#666",d:"M 5 6 L 13 6 L 9 10 z"})),_react2.default.createElement("ul",{className:"toolbar-select-options"+(r?" open":"")},n))}},{key:"_subscribe",value:function(){this._listener||(this._listener=this.handleClick.bind(this),document.addEventListener("click",this._listener))}},{key:"_release",value:function(){this._listener&&(document.removeEventListener("click",this._listener),this._listener=null)}},{key:"handleClick",value:function(e){this._node!==e.target&&(preventDefault(e),this.setState({visible:!1}),this._release())}}]),t}(_react2.default.Component)).propTypes={title:_propTypes2.default.string,label:_propTypes2.default.string,onSelect:_propTypes2.default.func},ToolbarSelectOption.propTypes={onSelect:_propTypes2.default.func,selected:_propTypes2.default.bool,label:_propTypes2.default.string,value:_propTypes2.default.any}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"prop-types":172}],20:[function(require,module,exports){(function(global){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.VariableEditor=void 0;var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_react2=_interopRequireDefault("undefined"!=typeof window?window.React:void 0!==global?global.React:null),_propTypes2=_interopRequireDefault(require("prop-types")),_onHasCompletion2=_interopRequireDefault(require("../utility/onHasCompletion"));(exports.VariableEditor=function(e){function t(e){_classCallCheck(this,t);var r=_possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return r._onKeyUp=function(e,t){var o=t.keyCode;(o>=65&&o<=90||!t.shiftKey&&o>=48&&o<=57||t.shiftKey&&189===o||t.shiftKey&&222===o)&&r.editor.execCommand("autocomplete")},r._onEdit=function(){r.ignoreChangeEvent||(r.cachedValue=r.editor.getValue(),r.props.onEdit&&r.props.onEdit(r.cachedValue))},r._onHasCompletion=function(e,t){(0,_onHasCompletion2.default)(e,t,r.props.onHintInformationRender)},r.cachedValue=e.value||"",r}return _inherits(t,e),_createClass(t,[{key:"componentDidMount",value:function(){var e=this,t=require("codemirror");require("codemirror/addon/hint/show-hint"),require("codemirror/addon/edit/matchbrackets"),require("codemirror/addon/edit/closebrackets"),require("codemirror/addon/fold/brace-fold"),require("codemirror/addon/fold/foldgutter"),require("codemirror/addon/lint/lint"),require("codemirror/keymap/sublime"),require("codemirror-graphql/variables/hint"),require("codemirror-graphql/variables/lint"),require("codemirror-graphql/variables/mode"),this.editor=t(this._node,{value:this.props.value||"",lineNumbers:!0,tabSize:2,mode:"graphql-variables",theme:this.props.editorTheme||"graphiql",keyMap:"sublime",autoCloseBrackets:!0,matchBrackets:!0,showCursorWhenSelecting:!0,foldGutter:{minFoldSize:4},lint:{variableToType:this.props.variableToType},hintOptions:{variableToType:this.props.variableToType},gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"],extraKeys:{"Cmd-Space":function(){return e.editor.showHint({completeSingle:!1})},"Ctrl-Space":function(){return e.editor.showHint({completeSingle:!1})},"Alt-Space":function(){return e.editor.showHint({completeSingle:!1})},"Shift-Space":function(){return e.editor.showHint({completeSingle:!1})},"Cmd-Enter":function(){e.props.onRunQuery&&e.props.onRunQuery()},"Ctrl-Enter":function(){e.props.onRunQuery&&e.props.onRunQuery()},"Ctrl-Left":"goSubwordLeft","Ctrl-Right":"goSubwordRight","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight"}}),this.editor.on("change",this._onEdit),this.editor.on("keyup",this._onKeyUp),this.editor.on("hasCompletion",this._onHasCompletion)}},{key:"componentDidUpdate",value:function(e){var t=require("codemirror");this.ignoreChangeEvent=!0,this.props.variableToType!==e.variableToType&&(this.editor.options.lint.variableToType=this.props.variableToType,this.editor.options.hintOptions.variableToType=this.props.variableToType,t.signal(this.editor,"change",this.editor)),this.props.value!==e.value&&this.props.value!==this.cachedValue&&(this.cachedValue=this.props.value,this.editor.setValue(this.props.value)),this.ignoreChangeEvent=!1}},{key:"componentWillUnmount",value:function(){this.editor.off("change",this._onEdit),this.editor.off("keyup",this._onKeyUp),this.editor.off("hasCompletion",this._onHasCompletion),this.editor=null}},{key:"render",value:function(){var e=this;return _react2.default.createElement("div",{className:"codemirrorWrap",ref:function(t){e._node=t}})}},{key:"getCodeMirror",value:function(){return this.editor}},{key:"getClientHeight",value:function(){return this._node&&this._node.clientHeight}}]),t}(_react2.default.Component)).propTypes={variableToType:_propTypes2.default.object,value:_propTypes2.default.string,onEdit:_propTypes2.default.func,onHintInformationRender:_propTypes2.default.func,onRunQuery:_propTypes2.default.func,editorTheme:_propTypes2.default.string}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utility/onHasCompletion":33,codemirror:63,"codemirror-graphql/variables/hint":48,"codemirror-graphql/variables/lint":49,"codemirror-graphql/variables/mode":50,"codemirror/addon/edit/closebrackets":53,"codemirror/addon/edit/matchbrackets":54,"codemirror/addon/fold/brace-fold":55,"codemirror/addon/fold/foldgutter":57,"codemirror/addon/hint/show-hint":58,"codemirror/addon/lint/lint":59,"codemirror/keymap/sublime":62,"prop-types":172}],21:[function(require,module,exports){"use strict";module.exports=require("./components/GraphiQL").GraphiQL},{"./components/GraphiQL":11}],22:[function(require,module,exports){"use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(r,t,n){return t&&e(r.prototype,t),n&&e(r,n),r}}(),CodeMirrorSizer=function(){function e(){_classCallCheck(this,e),this.sizes=[]}return _createClass(e,[{key:"updateSizes",value:function(e){var r=this;e.forEach(function(e,t){var n=e.getClientHeight();t<=r.sizes.length&&n!==r.sizes[t]&&e.getCodeMirror().setSize(),r.sizes[t]=n})}}]),e}();exports.default=CodeMirrorSizer},{}],23:[function(require,module,exports){"use strict";function _defineProperty(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}(),QueryStore=function(){function e(t,i){_classCallCheck(this,e),this.key=t,this.storage=i,this.items=this.fetchAll()}return _createClass(e,[{key:"contains",value:function(e){return this.items.some(function(t){return t.query===e.query&&t.variables===e.variables&&t.operationName===e.operationName})}},{key:"delete",value:function(e){var t=this.items.findIndex(function(t){return t.query===e.query&&t.variables===e.variables&&t.operationName===e.operationName});-1!==t&&(this.items.splice(t,1),this.save())}},{key:"fetchRecent",value:function(){return this.items[this.items.length-1]}},{key:"fetchAll",value:function(){var e=this.storage.get(this.key);return e?JSON.parse(e)[this.key]:[]}},{key:"push",value:function(e){this.items.push(e),this.save()}},{key:"shift",value:function(){this.items.shift(),this.save()}},{key:"save",value:function(){this.storage.set(this.key,JSON.stringify(_defineProperty({},this.key,this.items)))}},{key:"length",get:function(){return this.items.length}}]),e}();exports.default=QueryStore},{}],24:[function(require,module,exports){"use strict";function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function isStorageAvailable(e,t,r){try{return e.setItem(t,r),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&0!==e.length}}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r<t.length;r++){var a=t[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(t,r,a){return r&&e(t.prototype,r),a&&e(t,a),t}}(),StorageAPI=function(){function e(t){_classCallCheck(this,e),this.storage=t||window.localStorage}return _createClass(e,[{key:"get",value:function(e){if(this.storage){var t=this.storage.getItem("graphiql:"+e);if("null"!==t&&"undefined"!==t)return t;this.storage.removeItem("graphiql:"+e)}}},{key:"set",value:function(e,t){if(this.storage){var r="graphiql:"+e;t?isStorageAvailable(this.storage,r,t)&&this.storage.setItem(r,t):this.storage.removeItem(r)}}}]),e}();exports.default=StorageAPI},{}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(e,t){var u=void 0;return function(){var o=this,n=arguments;clearTimeout(u),u=setTimeout(function(){u=null,t.apply(o,n)},e)}}},{}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getLeft=function(e){for(var t=0,f=e;f.offsetParent;)t+=f.offsetLeft,f=f.offsetParent;return t},exports.getTop=function(e){for(var t=0,f=e;f.offsetParent;)t+=f.offsetTop,f=f.offsetParent;return t}},{}],27:[function(require,module,exports){"use strict";function defaultGetDefaultFieldNames(e){if(!e.getFields)return[];var t=e.getFields();if(t.id)return["id"];if(t.edges)return["edges"];if(t.node)return["node"];var r=[];return Object.keys(t).forEach(function(e){(0,_graphql.isLeafType)(t[e].type)&&r.push(e)}),r}function buildSelectionSet(e,t){var r=(0,_graphql.getNamedType)(e);if(e&&!(0,_graphql.isLeafType)(e)){var n=t(r);if(Array.isArray(n)&&0!==n.length)return{kind:"SelectionSet",selections:n.map(function(e){var n=r.getFields()[e];return{kind:"Field",name:{kind:"Name",value:e},selectionSet:buildSelectionSet(n?n.type:null,t)}})}}}function withInsertions(e,t){if(0===t.length)return e;var r="",n=0;return t.forEach(function(t){var i=t.index,a=t.string;r+=e.slice(n,i)+a,n=i}),r+=e.slice(n)}function getIndentation(e,t){for(var r=t,n=t;r;){var i=e.charCodeAt(r-1);if(10===i||13===i||8232===i||8233===i)break;r--,9!==i&&11!==i&&12!==i&&32!==i&&160!==i&&(n=r)}return e.substring(r,n)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.fillLeafs=function(e,t,r){var n=[];if(!e)return{insertions:n,result:t};var i=void 0;try{i=(0,_graphql.parse)(t)}catch(e){return{insertions:n,result:t}}var a=r||defaultGetDefaultFieldNames,l=new _graphql.TypeInfo(e);return(0,_graphql.visit)(i,{leave:function(e){l.leave(e)},enter:function(e){if(l.enter(e),"Field"===e.kind&&!e.selectionSet){var r=buildSelectionSet(l.getType(),a);if(r){var i=getIndentation(t,e.loc.start);n.push({index:e.loc.end,string:" "+(0,_graphql.print)(r).replace(/\n/g,"\n"+i)})}}}}),{insertions:n,result:withInsertions(t,n)}};var _graphql=require("graphql")},{graphql:92}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(e,t){for(var r=0;r<e.length;r++)if(t(e[r]))return e[r]}},{}],29:[function(require,module,exports){"use strict";function collectVariables(e,r){var a=Object.create(null);return r.definitions.forEach(function(r){if("OperationDefinition"===r.kind){var i=r.variableDefinitions;i&&i.forEach(function(r){var i=r.variable,t=r.type,n=(0,_graphql.typeFromAST)(e,t);n&&(a[i.name.value]=n)})}}),a}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(e,r){if(r){var a=void 0;try{a=(0,_graphql.parse)(r)}catch(e){return}var i=e?collectVariables(e,a):null,t=[];return a.definitions.forEach(function(e){"OperationDefinition"===e.kind&&t.push(e)}),{variableToType:i,operations:t}}},exports.collectVariables=collectVariables;var _graphql=require("graphql")},{graphql:92}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(e,t,n){if(n&&!(n.length<1)){var r=n.map(function(e){return e.name&&e.name.value});if(t&&-1!==r.indexOf(t))return t;if(t&&e){var a=e.map(function(e){return e.name&&e.name.value}).indexOf(t);if(-1!==a&&a<r.length)return r[a]}return r[0]}}},{}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _graphql=require("graphql");Object.defineProperty(exports,"introspectionQuery",{enumerable:!0,get:function(){return _graphql.introspectionQuery}});exports.introspectionQuerySansSubscriptions="\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n"},{graphql:92}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.normalizeWhitespace=function(e){return e.replace(sanitizeRegex," ")};var invalidCharacters=exports.invalidCharacters=Array.from({length:11},function(e,r){return String.fromCharCode(8192+r)}).concat(["\u2028","\u2029"," "]),sanitizeRegex=new RegExp("["+invalidCharacters.join("|")+"]","g")},{}],33:[function(require,module,exports){"use strict";function renderType(e){return e instanceof _graphql.GraphQLNonNull?renderType(e.ofType)+"!":e instanceof _graphql.GraphQLList?"["+renderType(e.ofType)+"]":'<a class="typeName">'+e.name+"</a>"}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(e,r,n){var a=void 0,i=void 0;require("codemirror").on(r,"select",function(e,r){if(!a){var t=r.parentNode;(a=document.createElement("div")).className="CodeMirror-hint-information",t.appendChild(a),(i=document.createElement("div")).className="CodeMirror-hint-deprecation",t.appendChild(i);var o=void 0;t.addEventListener("DOMNodeRemoved",o=function(e){e.target===t&&(t.removeEventListener("DOMNodeRemoved",o),a=null,i=null,o=null)})}var d=e.description?(0,_marked2.default)(e.description,{sanitize:!0}):"Self descriptive.",l=e.type?'<span class="infoType">'+renderType(e.type)+"</span>":"";if(a.innerHTML='<div class="content">'+("<p>"===d.slice(0,3)?"<p>"+l+d.slice(3):l+d)+"</div>",e.isDeprecated){var p=e.deprecationReason?(0,_marked2.default)(e.deprecationReason,{sanitize:!0}):"";i.innerHTML='<span class="deprecation-label">Deprecated</span>'+p,i.style.display="block"}else i.style.display="none";n&&n(a)})};var _graphql=require("graphql"),_marked2=function(e){return e&&e.__esModule?e:{default:e}}(require("marked"))},{codemirror:63,graphql:92,marked:167}],34:[function(require,module,exports){(function(global){"use strict";function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return x<y?-1:y<x?1:0}function isBuffer(b){return global.Buffer&&"function"==typeof global.Buffer.isBuffer?global.Buffer.isBuffer(b):!(null==b||!b._isBuffer)}function pToString(obj){return Object.prototype.toString.call(obj)}function isView(arrbuf){return!isBuffer(arrbuf)&&("function"==typeof global.ArrayBuffer&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(arrbuf):!!arrbuf&&(arrbuf instanceof DataView||!!(arrbuf.buffer&&arrbuf.buffer instanceof ArrayBuffer))))}function getName(func){if(util.isFunction(func)){if(functionsHaveNames)return func.name;var match=func.toString().match(regex);return match&&match[1]}}function truncate(s,n){return"string"==typeof s?s.length<n?s:s.slice(0,n):s}function inspect(something){if(functionsHaveNames||!util.isFunction(something))return util.inspect(something);var rawname=getName(something);return"[Function"+(rawname?": "+rawname:"")+"]"}function getMessage(self){return truncate(inspect(self.actual),128)+" "+self.operator+" "+truncate(inspect(self.expected),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}function ok(value,message){value||fail(value,!0,message,"==",assert.ok)}function _deepEqual(actual,expected,strict,memos){if(actual===expected)return!0;if(isBuffer(actual)&&isBuffer(expected))return 0===compare(actual,expected);if(util.isDate(actual)&&util.isDate(expected))return actual.getTime()===expected.getTime();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;if(null!==actual&&"object"==typeof actual||null!==expected&&"object"==typeof expected){if(isView(actual)&&isView(expected)&&pToString(actual)===pToString(expected)&&!(actual instanceof Float32Array||actual instanceof Float64Array))return 0===compare(new Uint8Array(actual.buffer),new Uint8Array(expected.buffer));if(isBuffer(actual)!==isBuffer(expected))return!1;var actualIndex=(memos=memos||{actual:[],expected:[]}).actual.indexOf(actual);return-1!==actualIndex&&actualIndex===memos.expected.indexOf(expected)||(memos.actual.push(actual),memos.expected.push(expected),objEquiv(actual,expected,strict,memos))}return strict?actual===expected:actual==expected}function isArguments(object){return"[object Arguments]"==Object.prototype.toString.call(object)}function objEquiv(a,b,strict,actualVisitedObjects){if(null===a||void 0===a||null===b||void 0===b)return!1;if(util.isPrimitive(a)||util.isPrimitive(b))return a===b;if(strict&&Object.getPrototypeOf(a)!==Object.getPrototypeOf(b))return!1;var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return!1;if(aIsArgs)return a=pSlice.call(a),b=pSlice.call(b),_deepEqual(a,b,strict);var key,i,ka=objectKeys(a),kb=objectKeys(b);if(ka.length!==kb.length)return!1;for(ka.sort(),kb.sort(),i=ka.length-1;i>=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=require("util/"),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames="foo"===function(){}.name,assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),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),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":176}],35:[function(require,module,exports){"use strict";var _codemirror2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("codemirror")),_graphqlLanguageServiceInterface=require("graphql-language-service-interface");_codemirror2.default.registerHelper("hint","graphql",function(editor,options){var schema=options.schema;if(schema){var cur=editor.getCursor(),token=editor.getTokenAt(cur),rawResults=(0,_graphqlLanguageServiceInterface.getAutocompleteSuggestions)(schema,editor.getValue(),cur,token),tokenStart=null!==token.type&&/"|\w/.test(token.string[0])?token.start:token.end,results={list:rawResults.map(function(item){return{text:item.label,type:schema.getType(item.detail),description:item.documentation,isDeprecated:item.isDeprecated,deprecationReason:item.deprecationReason}}),from:{line:cur.line,column:tokenStart},to:{line:cur.line,column:token.end}};return results&&results.list&&results.list.length>0&&(results.from=_codemirror2.default.Pos(results.from.line,results.from.column),results.to=_codemirror2.default.Pos(results.to.line,results.to.column),_codemirror2.default.signal(editor,"hasCompletion",editor,results,token)),results}})},{codemirror:63,"graphql-language-service-interface":73}],36:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function renderField(into,typeInfo,options){renderQualifiedField(into,typeInfo,options),renderTypeAnnotation(into,typeInfo,options,typeInfo.type)}function renderQualifiedField(into,typeInfo,options){var fieldName=typeInfo.fieldDef.name;"__"!==fieldName.slice(0,2)&&(renderType(into,typeInfo,options,typeInfo.parentType),text(into,".")),text(into,fieldName,"field-name",options,(0,_SchemaReference.getFieldReference)(typeInfo))}function renderDirective(into,typeInfo,options){text(into,"@"+typeInfo.directiveDef.name,"directive-name",options,(0,_SchemaReference.getDirectiveReference)(typeInfo))}function renderArg(into,typeInfo,options){typeInfo.directiveDef?renderDirective(into,typeInfo,options):typeInfo.fieldDef&&renderQualifiedField(into,typeInfo,options);var name=typeInfo.argDef.name;text(into,"("),text(into,name,"arg-name",options,(0,_SchemaReference.getArgumentReference)(typeInfo)),renderTypeAnnotation(into,typeInfo,options,typeInfo.inputType),text(into,")")}function renderTypeAnnotation(into,typeInfo,options,t){text(into,": "),renderType(into,typeInfo,options,t)}function renderEnumValue(into,typeInfo,options){var name=typeInfo.enumValue.name;renderType(into,typeInfo,options,typeInfo.inputType),text(into,"."),text(into,name,"enum-value",options,(0,_SchemaReference.getEnumValueReference)(typeInfo))}function renderType(into,typeInfo,options,t){t instanceof _graphql.GraphQLNonNull?(renderType(into,typeInfo,options,t.ofType),text(into,"!")):t instanceof _graphql.GraphQLList?(text(into,"["),renderType(into,typeInfo,options,t.ofType),text(into,"]")):text(into,t.name,"type-name",options,(0,_SchemaReference.getTypeReference)(typeInfo,t))}function renderDescription(into,options,def){var description=def.description;if(description){var descriptionDiv=document.createElement("div");descriptionDiv.className="info-description",options.renderDescription?descriptionDiv.innerHTML=options.renderDescription(description):descriptionDiv.appendChild(document.createTextNode(description)),into.appendChild(descriptionDiv)}renderDeprecation(into,options,def)}function renderDeprecation(into,options,def){var reason=def.deprecationReason;if(reason){var deprecationDiv=document.createElement("div");deprecationDiv.className="info-deprecation",options.renderDescription?deprecationDiv.innerHTML=options.renderDescription(reason):deprecationDiv.appendChild(document.createTextNode(reason));var label=document.createElement("span");label.className="info-deprecation-label",label.appendChild(document.createTextNode("Deprecated: ")),deprecationDiv.insertBefore(label,deprecationDiv.firstChild),into.appendChild(deprecationDiv)}}function text(into,content,className,options,ref){if(className){var onClick=options.onClick,node=document.createElement(onClick?"a":"span");onClick&&(node.href="javascript:void 0",node.addEventListener("click",function(e){onClick(ref,e)})),node.className=className,node.appendChild(document.createTextNode(content)),into.appendChild(node)}else into.appendChild(document.createTextNode(content))}var _graphql=require("graphql"),_codemirror2=_interopRequireDefault(require("codemirror")),_getTypeInfo2=_interopRequireDefault(require("./utils/getTypeInfo")),_SchemaReference=require("./utils/SchemaReference");require("./utils/info-addon"),_codemirror2.default.registerHelper("info","graphql",function(token,options){if(options.schema&&token.state){var state=token.state,kind=state.kind,step=state.step,typeInfo=(0,_getTypeInfo2.default)(options.schema,token.state);if("Field"===kind&&0===step&&typeInfo.fieldDef||"AliasedField"===kind&&2===step&&typeInfo.fieldDef){var into=document.createElement("div");return renderField(into,typeInfo,options),renderDescription(into,options,typeInfo.fieldDef),into}if("Directive"===kind&&1===step&&typeInfo.directiveDef){var _into=document.createElement("div");return renderDirective(_into,typeInfo,options),renderDescription(_into,options,typeInfo.directiveDef),_into}if("Argument"===kind&&0===step&&typeInfo.argDef){var _into2=document.createElement("div");return renderArg(_into2,typeInfo,options),renderDescription(_into2,options,typeInfo.argDef),_into2}if("EnumValue"===kind&&typeInfo.enumValue&&typeInfo.enumValue.description){var _into3=document.createElement("div");return renderEnumValue(_into3,typeInfo,options),renderDescription(_into3,options,typeInfo.enumValue),_into3}if("NamedType"===kind&&typeInfo.type&&typeInfo.type.description){var _into4=document.createElement("div");return renderType(_into4,typeInfo,options,typeInfo.type),renderDescription(_into4,options,typeInfo.type),_into4}}})},{"./utils/SchemaReference":41,"./utils/getTypeInfo":43,"./utils/info-addon":45,codemirror:63,graphql:92}],37:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _codemirror2=_interopRequireDefault(require("codemirror")),_getTypeInfo2=_interopRequireDefault(require("./utils/getTypeInfo")),_SchemaReference=require("./utils/SchemaReference");require("./utils/jump-addon"),_codemirror2.default.registerHelper("jump","graphql",function(token,options){if(options.schema&&options.onClick&&token.state){var state=token.state,kind=state.kind,step=state.step,typeInfo=(0,_getTypeInfo2.default)(options.schema,state);return"Field"===kind&&0===step&&typeInfo.fieldDef||"AliasedField"===kind&&2===step&&typeInfo.fieldDef?(0,_SchemaReference.getFieldReference)(typeInfo):"Directive"===kind&&1===step&&typeInfo.directiveDef?(0,_SchemaReference.getDirectiveReference)(typeInfo):"Argument"===kind&&0===step&&typeInfo.argDef?(0,_SchemaReference.getArgumentReference)(typeInfo):"EnumValue"===kind&&typeInfo.enumValue?(0,_SchemaReference.getEnumValueReference)(typeInfo):"NamedType"===kind&&typeInfo.type?(0,_SchemaReference.getTypeReference)(typeInfo):void 0}})},{"./utils/SchemaReference":41,"./utils/getTypeInfo":43,"./utils/jump-addon":47,codemirror:63}],38:[function(require,module,exports){"use strict";var _codemirror2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("codemirror")),_graphqlLanguageServiceInterface=require("graphql-language-service-interface"),SEVERITY=["error","warning","information","hint"],TYPE={"GraphQL: Validation":"validation","GraphQL: Deprecation":"deprecation","GraphQL: Syntax":"syntax"};_codemirror2.default.registerHelper("lint","graphql",function(text,options){var schema=options.schema;return(0,_graphqlLanguageServiceInterface.getDiagnostics)(text,schema).map(function(error){return{message:error.message,severity:SEVERITY[error.severity-1],type:TYPE[error.source],from:_codemirror2.default.Pos(error.range.start.line,error.range.start.character),to:_codemirror2.default.Pos(error.range.end.line,error.range.end.character)}})})},{codemirror:63,"graphql-language-service-interface":73}],39:[function(require,module,exports){"use strict";function indent(state,textAfter){var levels=state.levels;return(levels&&0!==levels.length?levels[levels.length-1]-(this.electricInput.test(textAfter)?1:0):state.indentLevel)*this.config.indentUnit}var _codemirror2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("codemirror")),_graphqlLanguageServiceParser=require("graphql-language-service-parser");_codemirror2.default.defineMode("graphql",function(config){var parser=(0,_graphqlLanguageServiceParser.onlineParser)({eatWhitespace:function(stream){return stream.eatWhile(_graphqlLanguageServiceParser.isIgnored)},lexRules:_graphqlLanguageServiceParser.LexRules,parseRules:_graphqlLanguageServiceParser.ParseRules,editorConfig:{tabSize:config.tabSize}});return{config:config,startState:parser.startState,token:parser.token,indent:indent,electricInput:/^\s*[})\]]/,fold:"brace",lineComment:"#",closeBrackets:{pairs:'()[]{}""',explode:"()[]{}"}}})},{codemirror:63,"graphql-language-service-parser":77}],40:[function(require,module,exports){"use strict";function indent(state,textAfter){var levels=state.levels;return(levels&&0!==levels.length?levels[levels.length-1]-(this.electricInput.test(textAfter)?1:0):state.indentLevel)*this.config.indentUnit}var _codemirror2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("codemirror")),_graphqlLanguageServiceParser=require("graphql-language-service-parser");_codemirror2.default.defineMode("graphql-results",function(config){var parser=(0,_graphqlLanguageServiceParser.onlineParser)({eatWhitespace:function(stream){return stream.eatSpace()},lexRules:LexRules,parseRules:ParseRules,editorConfig:{tabSize:config.tabSize}});return{config:config,startState:parser.startState,token:parser.token,indent:indent,electricInput:/^\s*[}\]]/,fold:"brace",closeBrackets:{pairs:'[]{}""',explode:"[]{}"}}});var LexRules={Punctuation:/^\[|]|\{|\}|:|,/,Number:/^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,String:/^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,Keyword:/^true|false|null/},ParseRules={Document:[(0,_graphqlLanguageServiceParser.p)("{"),(0,_graphqlLanguageServiceParser.list)("Entry",(0,_graphqlLanguageServiceParser.p)(",")),(0,_graphqlLanguageServiceParser.p)("}")],Entry:[(0,_graphqlLanguageServiceParser.t)("String","def"),(0,_graphqlLanguageServiceParser.p)(":"),"Value"],Value:function(token){switch(token.kind){case"Number":return"NumberValue";case"String":return"StringValue";case"Punctuation":switch(token.value){case"[":return"ListValue";case"{":return"ObjectValue"}return null;case"Keyword":switch(token.value){case"true":case"false":return"BooleanValue";case"null":return"NullValue"}return null}},NumberValue:[(0,_graphqlLanguageServiceParser.t)("Number","number")],StringValue:[(0,_graphqlLanguageServiceParser.t)("String","string")],BooleanValue:[(0,_graphqlLanguageServiceParser.t)("Keyword","builtin")],NullValue:[(0,_graphqlLanguageServiceParser.t)("Keyword","keyword")],ListValue:[(0,_graphqlLanguageServiceParser.p)("["),(0,_graphqlLanguageServiceParser.list)("Value",(0,_graphqlLanguageServiceParser.p)(",")),(0,_graphqlLanguageServiceParser.p)("]")],ObjectValue:[(0,_graphqlLanguageServiceParser.p)("{"),(0,_graphqlLanguageServiceParser.list)("ObjectField",(0,_graphqlLanguageServiceParser.p)(",")),(0,_graphqlLanguageServiceParser.p)("}")],ObjectField:[(0,_graphqlLanguageServiceParser.t)("String","property"),(0,_graphqlLanguageServiceParser.p)(":"),"Value"]}},{codemirror:63,"graphql-language-service-parser":77}],41:[function(require,module,exports){"use strict";function isMetaField(fieldDef){return"__"===fieldDef.name.slice(0,2)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getFieldReference=function(typeInfo){return{kind:"Field",schema:typeInfo.schema,field:typeInfo.fieldDef,type:isMetaField(typeInfo.fieldDef)?null:typeInfo.parentType}},exports.getDirectiveReference=function(typeInfo){return{kind:"Directive",schema:typeInfo.schema,directive:typeInfo.directiveDef}},exports.getArgumentReference=function(typeInfo){return typeInfo.directiveDef?{kind:"Argument",schema:typeInfo.schema,argument:typeInfo.argDef,directive:typeInfo.directiveDef}:{kind:"Argument",schema:typeInfo.schema,argument:typeInfo.argDef,field:typeInfo.fieldDef,type:isMetaField(typeInfo.fieldDef)?null:typeInfo.parentType}},exports.getEnumValueReference=function(typeInfo){return{kind:"EnumValue",value:typeInfo.enumValue,type:(0,_graphql.getNamedType)(typeInfo.inputType)}},exports.getTypeReference=function(typeInfo,type){return{kind:"Type",schema:typeInfo.schema,type:type||typeInfo.type}};var _graphql=require("graphql")},{graphql:92}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(stack,fn){for(var reverseStateStack=[],state=stack;state&&state.kind;)reverseStateStack.push(state),state=state.prevState;for(var i=reverseStateStack.length-1;i>=0;i--)fn(reverseStateStack[i])}},{}],43:[function(require,module,exports){"use strict";function getFieldDef(schema,type,fieldName){return fieldName===_introspection.SchemaMetaFieldDef.name&&schema.getQueryType()===type?_introspection.SchemaMetaFieldDef:fieldName===_introspection.TypeMetaFieldDef.name&&schema.getQueryType()===type?_introspection.TypeMetaFieldDef:fieldName===_introspection.TypeNameMetaFieldDef.name&&(0,_graphql.isCompositeType)(type)?_introspection.TypeNameMetaFieldDef:type.getFields?type.getFields()[fieldName]:void 0}function find(array,predicate){for(var i=0;i<array.length;i++)if(predicate(array[i]))return array[i]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(schema,tokenState){var info={schema:schema,type:null,parentType:null,inputType:null,directiveDef:null,fieldDef:null,argDef:null,argDefs:null,objectFieldDefs:null};return(0,_forEachState2.default)(tokenState,function(state){switch(state.kind){case"Query":case"ShortQuery":info.type=schema.getQueryType();break;case"Mutation":info.type=schema.getMutationType();break;case"Subscription":info.type=schema.getSubscriptionType();break;case"InlineFragment":case"FragmentDefinition":state.type&&(info.type=schema.getType(state.type));break;case"Field":case"AliasedField":info.fieldDef=info.type&&state.name?getFieldDef(schema,info.parentType,state.name):null,info.type=info.fieldDef&&info.fieldDef.type;break;case"SelectionSet":info.parentType=(0,_graphql.getNamedType)(info.type);break;case"Directive":info.directiveDef=state.name&&schema.getDirective(state.name);break;case"Arguments":var parentDef="Field"===state.prevState.kind?info.fieldDef:"Directive"===state.prevState.kind?info.directiveDef:"AliasedField"===state.prevState.kind?state.prevState.name&&getFieldDef(schema,info.parentType,state.prevState.name):null;info.argDefs=parentDef&&parentDef.args;break;case"Argument":if(info.argDef=null,info.argDefs)for(var i=0;i<info.argDefs.length;i++)if(info.argDefs[i].name===state.name){info.argDef=info.argDefs[i];break}info.inputType=info.argDef&&info.argDef.type;break;case"EnumValue":var enumType=(0,_graphql.getNamedType)(info.inputType);info.enumValue=enumType instanceof _graphql.GraphQLEnumType?find(enumType.getValues(),function(val){return val.value===state.name}):null;break;case"ListValue":var nullableType=(0,_graphql.getNullableType)(info.inputType);info.inputType=nullableType instanceof _graphql.GraphQLList?nullableType.ofType:null;break;case"ObjectValue":var objectType=(0,_graphql.getNamedType)(info.inputType);info.objectFieldDefs=objectType instanceof _graphql.GraphQLInputObjectType?objectType.getFields():null;break;case"ObjectField":var objectField=state.name&&info.objectFieldDefs?info.objectFieldDefs[state.name]:null;info.inputType=objectField&&objectField.type;break;case"NamedType":info.type=schema.getType(state.name)}}),info};var _graphql=require("graphql"),_introspection=require("graphql/type/introspection"),_forEachState2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("./forEachState"))},{"./forEachState":42,graphql:92,"graphql/type/introspection":115}],44:[function(require,module,exports){"use strict";function filterAndSortList(list,text){return text?filterNonEmpty(filterNonEmpty(list.map(function(entry){return{proximity:getProximity(normalizeText(entry.text),text),entry:entry}}),function(pair){return pair.proximity<=2}),function(pair){return!pair.entry.isDeprecated}).sort(function(a,b){return(a.entry.isDeprecated?1:0)-(b.entry.isDeprecated?1:0)||a.proximity-b.proximity||a.entry.text.length-b.entry.text.length}).map(function(pair){return pair.entry}):filterNonEmpty(list,function(entry){return!entry.isDeprecated})}function filterNonEmpty(array,predicate){var filtered=array.filter(predicate);return 0===filtered.length?array:filtered}function normalizeText(text){return text.toLowerCase().replace(/\W/g,"")}function getProximity(suggestion,text){var proximity=lexicalDistance(text,suggestion);return suggestion.length>text.length&&(proximity-=suggestion.length-text.length-1,proximity+=0===suggestion.indexOf(text)?0:.5),proximity}function lexicalDistance(a,b){var i=void 0,j=void 0,d=[],aLength=a.length,bLength=b.length;for(i=0;i<=aLength;i++)d[i]=[i];for(j=1;j<=bLength;j++)d[0][j]=j;for(i=1;i<=aLength;i++)for(j=1;j<=bLength;j++){var cost=a[i-1]===b[j-1]?0:1;d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+cost),i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1]&&(d[i][j]=Math.min(d[i][j],d[i-2][j-2]+cost))}return d[aLength][bLength]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(cursor,token,list){var hints=filterAndSortList(list,normalizeText(token.string));if(hints){var tokenStart=null!==token.type&&/"|\w/.test(token.string[0])?token.start:token.end;return{list:hints,from:{line:cursor.line,column:tokenStart},to:{line:cursor.line,column:token.end}}}}},{}],45:[function(require,module,exports){"use strict";function createState(options){return{options:options instanceof Function?{render:options}:!0===options?{}:options}}function getHoverTime(cm){var options=cm.state.info.options;return options&&options.hoverTime||500}function onMouseOver(cm,e){var state=cm.state.info,target=e.target||e.srcElement;if("SPAN"===target.nodeName&&void 0===state.hoverTimeout){var box=target.getBoundingClientRect(),hoverTime=getHoverTime(cm);state.hoverTimeout=setTimeout(onHover,hoverTime);var onMouseMove=function(){clearTimeout(state.hoverTimeout),state.hoverTimeout=setTimeout(onHover,hoverTime)},onMouseOut=function onMouseOut(){_codemirror2.default.off(document,"mousemove",onMouseMove),_codemirror2.default.off(cm.getWrapperElement(),"mouseout",onMouseOut),clearTimeout(state.hoverTimeout),state.hoverTimeout=void 0},onHover=function(){_codemirror2.default.off(document,"mousemove",onMouseMove),_codemirror2.default.off(cm.getWrapperElement(),"mouseout",onMouseOut),state.hoverTimeout=void 0,onMouseHover(cm,box)};_codemirror2.default.on(document,"mousemove",onMouseMove),_codemirror2.default.on(cm.getWrapperElement(),"mouseout",onMouseOut)}}function onMouseHover(cm,box){var pos=cm.coordsChar({left:(box.left+box.right)/2,top:(box.top+box.bottom)/2}),options=cm.state.info.options,render=options.render||cm.getHelper(pos,"info");if(render){var token=cm.getTokenAt(pos,!0);if(token){var info=render(token,options,cm);info&&showPopup(cm,box,info)}}}function showPopup(cm,box,info){var popup=document.createElement("div");popup.className="CodeMirror-info",popup.appendChild(info),document.body.appendChild(popup);var popupBox=popup.getBoundingClientRect(),popupStyle=popup.currentStyle||window.getComputedStyle(popup),popupWidth=popupBox.right-popupBox.left+parseFloat(popupStyle.marginLeft)+parseFloat(popupStyle.marginRight),popupHeight=popupBox.bottom-popupBox.top+parseFloat(popupStyle.marginTop)+parseFloat(popupStyle.marginBottom),topPos=box.bottom;popupHeight>window.innerHeight-box.bottom-15&&box.top>window.innerHeight-box.bottom&&(topPos=box.top-popupHeight),topPos<0&&(topPos=box.bottom);var leftPos=Math.max(0,window.innerWidth-popupWidth-15);leftPos>box.left&&(leftPos=box.left),popup.style.opacity=1,popup.style.top=topPos+"px",popup.style.left=leftPos+"px";var popupTimeout=void 0,onMouseOverPopup=function(){clearTimeout(popupTimeout)},onMouseOut=function(){clearTimeout(popupTimeout),popupTimeout=setTimeout(hidePopup,200)},hidePopup=function(){_codemirror2.default.off(popup,"mouseover",onMouseOverPopup),_codemirror2.default.off(popup,"mouseout",onMouseOut),_codemirror2.default.off(cm.getWrapperElement(),"mouseout",onMouseOut),popup.style.opacity?(popup.style.opacity=0,setTimeout(function(){popup.parentNode&&popup.parentNode.removeChild(popup)},600)):popup.parentNode&&popup.parentNode.removeChild(popup)};_codemirror2.default.on(popup,"mouseover",onMouseOverPopup),_codemirror2.default.on(popup,"mouseout",onMouseOut),_codemirror2.default.on(cm.getWrapperElement(),"mouseout",onMouseOut)}var _codemirror2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("codemirror"));_codemirror2.default.defineOption("info",!1,function(cm,options,old){if(old&&old!==_codemirror2.default.Init){var oldOnMouseOver=cm.state.info.onMouseOver;_codemirror2.default.off(cm.getWrapperElement(),"mouseover",oldOnMouseOver),clearTimeout(cm.state.info.hoverTimeout),delete cm.state.info}if(options){var state=cm.state.info=createState(options);state.onMouseOver=onMouseOver.bind(null,cm),_codemirror2.default.on(cm.getWrapperElement(),"mouseover",state.onMouseOver)}})},{codemirror:63}],46:[function(require,module,exports){"use strict";function parseObj(){var nodeStart=start,members=[];if(expect("{"),!skip("}")){do{members.push(parseMember())}while(skip(","));expect("}")}return{kind:"Object",start:nodeStart,end:lastEnd,members:members}}function parseMember(){var nodeStart=start,key="String"===kind?curToken():null;expect("String"),expect(":");var value=parseVal();return{kind:"Member",start:nodeStart,end:lastEnd,key:key,value:value}}function parseArr(){var nodeStart=start,values=[];if(expect("["),!skip("]")){do{values.push(parseVal())}while(skip(","));expect("]")}return{kind:"Array",start:nodeStart,end:lastEnd,values:values}}function parseVal(){switch(kind){case"[":return parseArr();case"{":return parseObj();case"String":case"Number":case"Boolean":case"Null":var token=curToken();return lex(),token}return expect("Value")}function curToken(){return{kind:kind,start:start,end:end,value:JSON.parse(string.slice(start,end))}}function expect(str){if(kind!==str){var found=void 0;if("EOF"===kind)found="[end of file]";else if(end-start>1)found="`"+string.slice(start,end)+"`";else{var match=string.slice(start).match(/^.+?\b/);found="`"+(match?match[0]:string[start])+"`"}throw syntaxError("Expected "+str+" but found "+found+".")}lex()}function syntaxError(message){return{message:message,start:start,end:end}}function skip(k){if(kind===k)return lex(),!0}function ch(){end<strLen&&(code=++end===strLen?0:string.charCodeAt(end))}function lex(){for(lastEnd=end;9===code||10===code||13===code||32===code;)ch();if(0!==code){switch(start=end,code){case 34:return kind="String",readString();case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return kind="Number",readNumber();case 102:if("false"!==string.slice(start,start+5))break;return end+=4,ch(),void(kind="Boolean");case 110:if("null"!==string.slice(start,start+4))break;return end+=3,ch(),void(kind="Null");case 116:if("true"!==string.slice(start,start+4))break;return end+=3,ch(),void(kind="Boolean")}kind=string[start],ch()}else kind="EOF"}function readString(){for(ch();34!==code&&code>31;)if(92===code)switch(ch(),code){case 34:case 47:case 92:case 98:case 102:case 110:case 114:case 116:ch();break;case 117:ch(),readHex(),readHex(),readHex(),readHex();break;default:throw syntaxError("Bad character escape sequence.")}else{if(end===strLen)throw syntaxError("Unterminated string.");ch()}if(34!==code)throw syntaxError("Unterminated string.");ch()}function readHex(){if(code>=48&&code<=57||code>=65&&code<=70||code>=97&&code<=102)return ch();throw syntaxError("Expected hexadecimal digit.")}function readNumber(){45===code&&ch(),48===code?ch():readDigits(),46===code&&(ch(),readDigits()),69!==code&&101!==code||(ch(),43!==code&&45!==code||ch(),readDigits())}function readDigits(){if(code<48||code>57)throw syntaxError("Expected decimal digit.");do{ch()}while(code>=48&&code<=57)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(str){string=str,strLen=str.length,start=end=lastEnd=-1,ch(),lex();var ast=parseObj();return expect("EOF"),ast};var string=void 0,strLen=void 0,start=void 0,end=void 0,lastEnd=void 0,code=void 0,kind=void 0},{}],47:[function(require,module,exports){"use strict";function onMouseOver(cm,event){var target=event.target||event.srcElement;if("SPAN"===target.nodeName){var box=target.getBoundingClientRect(),cursor={left:(box.left+box.right)/2,top:(box.top+box.bottom)/2};cm.state.jump.cursor=cursor,cm.state.jump.isHoldingModifier&&enableJumpMode(cm)}}function onMouseOut(cm){cm.state.jump.isHoldingModifier||!cm.state.jump.cursor?cm.state.jump.isHoldingModifier&&cm.state.jump.marker&&disableJumpMode(cm):cm.state.jump.cursor=null}function onKeyDown(cm,event){if(!cm.state.jump.isHoldingModifier&&isJumpModifier(event.key)){cm.state.jump.isHoldingModifier=!0,cm.state.jump.cursor&&enableJumpMode(cm);var onClick=function(clickEvent){var destination=cm.state.jump.destination;destination&&cm.state.jump.options.onClick(destination,clickEvent)},onMouseDown=function(_,downEvent){cm.state.jump.destination&&(downEvent.codemirrorIgnore=!0)};_codemirror2.default.on(document,"keyup",function onKeyUp(upEvent){upEvent.code===event.code&&(cm.state.jump.isHoldingModifier=!1,cm.state.jump.marker&&disableJumpMode(cm),_codemirror2.default.off(document,"keyup",onKeyUp),_codemirror2.default.off(document,"click",onClick),cm.off("mousedown",onMouseDown))}),_codemirror2.default.on(document,"click",onClick),cm.on("mousedown",onMouseDown)}}function isJumpModifier(key){return key===(isMac?"Meta":"Control")}function enableJumpMode(cm){if(!cm.state.jump.marker){var cursor=cm.state.jump.cursor,pos=cm.coordsChar(cursor),token=cm.getTokenAt(pos,!0),options=cm.state.jump.options,getDestination=options.getDestination||cm.getHelper(pos,"jump");if(getDestination){var destination=getDestination(token,options,cm);if(destination){var marker=cm.markText({line:pos.line,ch:token.start},{line:pos.line,ch:token.end},{className:"CodeMirror-jump-token"});cm.state.jump.marker=marker,cm.state.jump.destination=destination}}}}function disableJumpMode(cm){var marker=cm.state.jump.marker;cm.state.jump.marker=null,cm.state.jump.destination=null,marker.clear()}var _codemirror2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("codemirror"));_codemirror2.default.defineOption("jump",!1,function(cm,options,old){if(old&&old!==_codemirror2.default.Init){var oldOnMouseOver=cm.state.jump.onMouseOver;_codemirror2.default.off(cm.getWrapperElement(),"mouseover",oldOnMouseOver);var oldOnMouseOut=cm.state.jump.onMouseOut;_codemirror2.default.off(cm.getWrapperElement(),"mouseout",oldOnMouseOut),_codemirror2.default.off(document,"keydown",cm.state.jump.onKeyDown),delete cm.state.jump}if(options){var state=cm.state.jump={options:options,onMouseOver:onMouseOver.bind(null,cm),onMouseOut:onMouseOut.bind(null,cm),onKeyDown:onKeyDown.bind(null,cm)};_codemirror2.default.on(cm.getWrapperElement(),"mouseover",state.onMouseOver),_codemirror2.default.on(cm.getWrapperElement(),"mouseout",state.onMouseOut),_codemirror2.default.on(document,"keydown",state.onKeyDown)}});var isMac=navigator&&-1!==navigator.appVersion.indexOf("Mac")},{codemirror:63}],48:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function getVariablesHint(cur,token,options){var state="Invalid"===token.state.kind?token.state.prevState:token.state,kind=state.kind,step=state.step;if("Document"===kind&&0===step)return(0,_hintList2.default)(cur,token,[{text:"{"}]);var variableToType=options.variableToType;if(variableToType){var typeInfo=getTypeInfo(variableToType,token.state);if("Document"===kind||"Variable"===kind&&0===step){var variableNames=Object.keys(variableToType);return(0,_hintList2.default)(cur,token,variableNames.map(function(name){return{text:'"'+name+'": ',type:variableToType[name]}}))}if(("ObjectValue"===kind||"ObjectField"===kind&&0===step)&&typeInfo.fields){var inputFields=Object.keys(typeInfo.fields).map(function(fieldName){return typeInfo.fields[fieldName]});return(0,_hintList2.default)(cur,token,inputFields.map(function(field){return{text:'"'+field.name+'": ',type:field.type,description:field.description}}))}if("StringValue"===kind||"NumberValue"===kind||"BooleanValue"===kind||"NullValue"===kind||"ListValue"===kind&&1===step||"ObjectField"===kind&&2===step||"Variable"===kind&&2===step){var namedInputType=(0,_graphql.getNamedType)(typeInfo.type);if(namedInputType instanceof _graphql.GraphQLInputObjectType)return(0,_hintList2.default)(cur,token,[{text:"{"}]);if(namedInputType instanceof _graphql.GraphQLEnumType){var valueMap=namedInputType.getValues(),values=Object.keys(valueMap).map(function(name){return valueMap[name]});return(0,_hintList2.default)(cur,token,values.map(function(value){return{text:'"'+value.name+'"',type:namedInputType,description:value.description}}))}if(namedInputType===_graphql.GraphQLBoolean)return(0,_hintList2.default)(cur,token,[{text:"true",type:_graphql.GraphQLBoolean,description:"Not false."},{text:"false",type:_graphql.GraphQLBoolean,description:"Not true."}])}}}function getTypeInfo(variableToType,tokenState){var info={type:null,fields:null};return(0,_forEachState2.default)(tokenState,function(state){if("Variable"===state.kind)info.type=variableToType[state.name];else if("ListValue"===state.kind){var nullableType=(0,_graphql.getNullableType)(info.type);info.type=nullableType instanceof _graphql.GraphQLList?nullableType.ofType:null}else if("ObjectValue"===state.kind){var objectType=(0,_graphql.getNamedType)(info.type);info.fields=objectType instanceof _graphql.GraphQLInputObjectType?objectType.getFields():null}else if("ObjectField"===state.kind){var objectField=state.name&&info.fields?info.fields[state.name]:null;info.type=objectField&&objectField.type}}),info}var _codemirror2=_interopRequireDefault(require("codemirror")),_graphql=require("graphql"),_forEachState2=_interopRequireDefault(require("../utils/forEachState")),_hintList2=_interopRequireDefault(require("../utils/hintList"));_codemirror2.default.registerHelper("hint","graphql-variables",function(editor,options){var cur=editor.getCursor(),token=editor.getTokenAt(cur),results=getVariablesHint(cur,token,options);return results&&results.list&&results.list.length>0&&(results.from=_codemirror2.default.Pos(results.from.line,results.from.column),results.to=_codemirror2.default.Pos(results.to.line,results.to.column),_codemirror2.default.signal(editor,"hasCompletion",editor,results,token)),results})},{"../utils/forEachState":42,"../utils/hintList":44,codemirror:63,graphql:92}],49:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function validateVariables(editor,variableToType,variablesAST){var errors=[];return variablesAST.members.forEach(function(member){var variableName=member.key.value,type=variableToType[variableName];type?validateValue(type,member.value).forEach(function(_ref){var node=_ref[0],message=_ref[1];errors.push(lintError(editor,node,message))}):errors.push(lintError(editor,member.key,'Variable "$'+variableName+'" does not appear in any GraphQL query.'))}),errors}function validateValue(type,valueAST){if(type instanceof _graphql.GraphQLNonNull)return"Null"===valueAST.kind?[[valueAST,'Type "'+type+'" is non-nullable and cannot be null.']]:validateValue(type.ofType,valueAST);if("Null"===valueAST.kind)return[];if(type instanceof _graphql.GraphQLList){var itemType=type.ofType;return"Array"===valueAST.kind?mapCat(valueAST.values,function(item){return validateValue(itemType,item)}):validateValue(itemType,valueAST)}if(type instanceof _graphql.GraphQLInputObjectType){if("Object"!==valueAST.kind)return[[valueAST,'Type "'+type+'" must be an Object.']];var providedFields=Object.create(null),fieldErrors=mapCat(valueAST.members,function(member){var fieldName=member.key.value;providedFields[fieldName]=!0;var inputField=type.getFields()[fieldName];return inputField?validateValue(inputField?inputField.type:void 0,member.value):[[member.key,'Type "'+type+'" does not have a field "'+fieldName+'".']]});return Object.keys(type.getFields()).forEach(function(fieldName){providedFields[fieldName]||type.getFields()[fieldName].type instanceof _graphql.GraphQLNonNull&&fieldErrors.push([valueAST,'Object of type "'+type+'" is missing required field "'+fieldName+'".'])}),fieldErrors}return"Boolean"===type.name&&"Boolean"!==valueAST.kind||"String"===type.name&&"String"!==valueAST.kind||"ID"===type.name&&"Number"!==valueAST.kind&&"String"!==valueAST.kind||"Float"===type.name&&"Number"!==valueAST.kind||"Int"===type.name&&("Number"!==valueAST.kind||(0|valueAST.value)!==valueAST.value)?[[valueAST,'Expected value of type "'+type+'".']]:(type instanceof _graphql.GraphQLEnumType||type instanceof _graphql.GraphQLScalarType)&&("String"!==valueAST.kind&&"Number"!==valueAST.kind&&"Boolean"!==valueAST.kind&&"Null"!==valueAST.kind||isNullish(type.parseValue(valueAST.value)))?[[valueAST,'Expected value of type "'+type+'".']]:[]}function lintError(editor,node,message){return{message:message,severity:"error",type:"validation",from:editor.posFromIndex(node.start),to:editor.posFromIndex(node.end)}}function isNullish(value){return null===value||void 0===value||value!==value}function mapCat(array,mapper){return Array.prototype.concat.apply([],array.map(mapper))}var _codemirror2=_interopRequireDefault(require("codemirror")),_graphql=require("graphql"),_jsonParse2=_interopRequireDefault(require("../utils/jsonParse"));_codemirror2.default.registerHelper("lint","graphql-variables",function(text,options,editor){if(!text)return[];var ast=void 0;try{ast=(0,_jsonParse2.default)(text)}catch(syntaxError){if(syntaxError.stack)throw syntaxError;return[lintError(editor,syntaxError,syntaxError.message)]}var variableToType=options.variableToType;return variableToType?validateVariables(editor,variableToType,ast):[]})},{"../utils/jsonParse":46,codemirror:63,graphql:92}],50:[function(require,module,exports){"use strict";function indent(state,textAfter){var levels=state.levels;return(levels&&0!==levels.length?levels[levels.length-1]-(this.electricInput.test(textAfter)?1:0):state.indentLevel)*this.config.indentUnit}function namedKey(style){return{style:style,match:function(token){return"String"===token.kind},update:function(state,token){state.name=token.value.slice(1,-1)}}}var _codemirror2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("codemirror")),_graphqlLanguageServiceParser=require("graphql-language-service-parser");_codemirror2.default.defineMode("graphql-variables",function(config){var parser=(0,_graphqlLanguageServiceParser.onlineParser)({eatWhitespace:function(stream){return stream.eatSpace()},lexRules:LexRules,parseRules:ParseRules,editorConfig:{tabSize:config.tabSize}});return{config:config,startState:parser.startState,token:parser.token,indent:indent,electricInput:/^\s*[}\]]/,fold:"brace",closeBrackets:{pairs:'[]{}""',explode:"[]{}"}}});var LexRules={Punctuation:/^\[|]|\{|\}|:|,/,Number:/^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,String:/^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,Keyword:/^true|false|null/},ParseRules={Document:[(0,_graphqlLanguageServiceParser.p)("{"),(0,_graphqlLanguageServiceParser.list)("Variable",(0,_graphqlLanguageServiceParser.opt)((0,_graphqlLanguageServiceParser.p)(","))),(0,_graphqlLanguageServiceParser.p)("}")],Variable:[namedKey("variable"),(0,_graphqlLanguageServiceParser.p)(":"),"Value"],Value:function(token){switch(token.kind){case"Number":return"NumberValue";case"String":return"StringValue";case"Punctuation":switch(token.value){case"[":return"ListValue";case"{":return"ObjectValue"}return null;case"Keyword":switch(token.value){case"true":case"false":return"BooleanValue";case"null":return"NullValue"}return null}},NumberValue:[(0,_graphqlLanguageServiceParser.t)("Number","number")],StringValue:[(0,_graphqlLanguageServiceParser.t)("String","string")],BooleanValue:[(0,_graphqlLanguageServiceParser.t)("Keyword","builtin")],NullValue:[(0,_graphqlLanguageServiceParser.t)("Keyword","keyword")],ListValue:[(0,_graphqlLanguageServiceParser.p)("["),(0,_graphqlLanguageServiceParser.list)("Value",(0,_graphqlLanguageServiceParser.opt)((0,_graphqlLanguageServiceParser.p)(","))),(0,_graphqlLanguageServiceParser.p)("]")],ObjectValue:[(0,_graphqlLanguageServiceParser.p)("{"),(0,_graphqlLanguageServiceParser.list)("ObjectField",(0,_graphqlLanguageServiceParser.opt)((0,_graphqlLanguageServiceParser.p)(","))),(0,_graphqlLanguageServiceParser.p)("}")],ObjectField:[namedKey("attribute"),(0,_graphqlLanguageServiceParser.p)(":"),"Value"]}},{codemirror:63,"graphql-language-service-parser":77}],51:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){"use strict";function firstNonWS(str){var found=str.search(nonWS);return-1==found?0:found}function probablyInsideString(cm,pos,line){return/\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line,0)))&&!/^[\'\"\`]/.test(line)}function getMode(cm,pos){var mode=cm.getMode();return!1!==mode.useInnerComments&&mode.innerMode?cm.getModeAt(pos):mode}var noOptions={},nonWS=/[^\s\u00a0]/,Pos=CodeMirror.Pos;CodeMirror.commands.toggleComment=function(cm){cm.toggleComment()},CodeMirror.defineExtension("toggleComment",function(options){options||(options=noOptions);for(var cm=this,minLine=1/0,ranges=this.listSelections(),mode=null,i=ranges.length-1;i>=0;i--){var from=ranges[i].from(),to=ranges[i].to();from.line>=minLine||(to.line>=minLine&&(to=Pos(minLine,0)),minLine=from.line,null==mode?cm.uncomment(from,to,options)?mode="un":(cm.lineComment(from,to,options),mode="line"):"un"==mode?cm.uncomment(from,to,options):cm.lineComment(from,to,options))}}),CodeMirror.defineExtension("lineComment",function(from,to,options){options||(options=noOptions);var self=this,mode=getMode(self,from),firstLine=self.getLine(from.line);if(null!=firstLine&&!probablyInsideString(self,from,firstLine)){var commentString=options.lineComment||mode.lineComment;if(commentString){var end=Math.min(0!=to.ch||to.line==from.line?to.line+1:to.line,self.lastLine()+1),pad=null==options.padding?" ":options.padding,blankLines=options.commentBlankLines||from.line==to.line;self.operation(function(){if(options.indent){for(var baseString=null,i=from.line;i<end;++i){var whitespace=(line=self.getLine(i)).slice(0,firstNonWS(line));(null==baseString||baseString.length>whitespace.length)&&(baseString=whitespace)}for(i=from.line;i<end;++i){var line=self.getLine(i),cut=baseString.length;(blankLines||nonWS.test(line))&&(line.slice(0,cut)!=baseString&&(cut=firstNonWS(line)),self.replaceRange(baseString+commentString+pad,Pos(i,0),Pos(i,cut)))}}else for(i=from.line;i<end;++i)(blankLines||nonWS.test(self.getLine(i)))&&self.replaceRange(commentString+pad,Pos(i,0))})}else(options.blockCommentStart||mode.blockCommentStart)&&(options.fullLines=!0,self.blockComment(from,to,options))}}),CodeMirror.defineExtension("blockComment",function(from,to,options){options||(options=noOptions);var self=this,mode=getMode(self,from),startString=options.blockCommentStart||mode.blockCommentStart,endString=options.blockCommentEnd||mode.blockCommentEnd;if(startString&&endString){if(!/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line,0)))){var end=Math.min(to.line,self.lastLine());end!=from.line&&0==to.ch&&nonWS.test(self.getLine(end))&&--end;var pad=null==options.padding?" ":options.padding;from.line>end||self.operation(function(){if(0!=options.fullLines){var lastLineHasText=nonWS.test(self.getLine(end));self.replaceRange(pad+endString,Pos(end)),self.replaceRange(startString+pad,Pos(from.line,0));var lead=options.blockCommentLead||mode.blockCommentLead;if(null!=lead)for(var i=from.line+1;i<=end;++i)(i!=end||lastLineHasText)&&self.replaceRange(lead+pad,Pos(i,0))}else self.replaceRange(endString,to),self.replaceRange(startString,from)})}}else(options.lineComment||mode.lineComment)&&0!=options.fullLines&&self.lineComment(from,to,options)}),CodeMirror.defineExtension("uncomment",function(from,to,options){options||(options=noOptions);var didSomething,self=this,mode=getMode(self,from),end=Math.min(0!=to.ch||to.line==from.line?to.line:to.line-1,self.lastLine()),start=Math.min(from.line,end),lineString=options.lineComment||mode.lineComment,lines=[],pad=null==options.padding?" ":options.padding;lineComment:if(lineString){for(var i=start;i<=end;++i){var line=self.getLine(i),found=line.indexOf(lineString);if(found>-1&&!/comment/.test(self.getTokenTypeAt(Pos(i,found+1)))&&(found=-1),-1==found&&nonWS.test(line))break lineComment;if(found>-1&&nonWS.test(line.slice(0,found)))break lineComment;lines.push(line)}if(self.operation(function(){for(var i=start;i<=end;++i){var line=lines[i-start],pos=line.indexOf(lineString),endPos=pos+lineString.length;pos<0||(line.slice(endPos,endPos+pad.length)==pad&&(endPos+=pad.length),didSomething=!0,self.replaceRange("",Pos(i,pos),Pos(i,endPos)))}}),didSomething)return!0}var startString=options.blockCommentStart||mode.blockCommentStart,endString=options.blockCommentEnd||mode.blockCommentEnd;if(!startString||!endString)return!1;var lead=options.blockCommentLead||mode.blockCommentLead,startLine=self.getLine(start),open=startLine.indexOf(startString);if(-1==open)return!1;var endLine=end==start?startLine:self.getLine(end),close=endLine.indexOf(endString,end==start?open+startString.length:0);-1==close&&start!=end&&(endLine=self.getLine(--end),close=endLine.indexOf(endString));var insideStart=Pos(start,open+1),insideEnd=Pos(end,close+1);if(-1==close||!/comment/.test(self.getTokenTypeAt(insideStart))||!/comment/.test(self.getTokenTypeAt(insideEnd))||self.getRange(insideStart,insideEnd,"\n").indexOf(endString)>-1)return!1;var lastStart=startLine.lastIndexOf(startString,from.ch),firstEnd=-1==lastStart?-1:startLine.slice(0,from.ch).indexOf(endString,lastStart+startString.length);if(-1!=lastStart&&-1!=firstEnd&&firstEnd+endString.length!=from.ch)return!1;firstEnd=endLine.indexOf(endString,to.ch);var almostLastStart=endLine.slice(to.ch).lastIndexOf(startString,firstEnd-to.ch);return lastStart=-1==firstEnd||-1==almostLastStart?-1:to.ch+almostLastStart,(-1==firstEnd||-1==lastStart||lastStart==to.ch)&&(self.operation(function(){self.replaceRange("",Pos(end,close-(pad&&endLine.slice(close-pad.length,close)==pad?pad.length:0)),Pos(end,close+endString.length));var openEnd=open+startString.length;if(pad&&startLine.slice(openEnd,openEnd+pad.length)==pad&&(openEnd+=pad.length),self.replaceRange("",Pos(start,open),Pos(start,openEnd)),lead)for(var i=start+1;i<=end;++i){var line=self.getLine(i),found=line.indexOf(lead);if(-1!=found&&!nonWS.test(line.slice(0,found))){var foundEnd=found+lead.length;pad&&line.slice(foundEnd,foundEnd+pad.length)==pad&&(foundEnd+=pad.length),self.replaceRange("",Pos(i,found),Pos(i,foundEnd))}}}),!0)})})},{"../../lib/codemirror":63}],52:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){function dialogDiv(cm,template,bottom){var dialog;return dialog=cm.getWrapperElement().appendChild(document.createElement("div")),dialog.className=bottom?"CodeMirror-dialog CodeMirror-dialog-bottom":"CodeMirror-dialog CodeMirror-dialog-top","string"==typeof template?dialog.innerHTML=template:dialog.appendChild(template),dialog}function closeNotification(cm,newVal){cm.state.currentNotificationClose&&cm.state.currentNotificationClose(),cm.state.currentNotificationClose=newVal}CodeMirror.defineExtension("openDialog",function(template,callback,options){function close(newVal){if("string"==typeof newVal)inp.value=newVal;else{if(closed)return;closed=!0,dialog.parentNode.removeChild(dialog),me.focus(),options.onClose&&options.onClose(dialog)}}options||(options={}),closeNotification(this,null);var button,dialog=dialogDiv(this,template,options.bottom),closed=!1,me=this,inp=dialog.getElementsByTagName("input")[0];return inp?(inp.focus(),options.value&&(inp.value=options.value,!1!==options.selectValueOnOpen&&inp.select()),options.onInput&&CodeMirror.on(inp,"input",function(e){options.onInput(e,inp.value,close)}),options.onKeyUp&&CodeMirror.on(inp,"keyup",function(e){options.onKeyUp(e,inp.value,close)}),CodeMirror.on(inp,"keydown",function(e){options&&options.onKeyDown&&options.onKeyDown(e,inp.value,close)||((27==e.keyCode||!1!==options.closeOnEnter&&13==e.keyCode)&&(inp.blur(),CodeMirror.e_stop(e),close()),13==e.keyCode&&callback(inp.value,e))}),!1!==options.closeOnBlur&&CodeMirror.on(inp,"blur",close)):(button=dialog.getElementsByTagName("button")[0])&&(CodeMirror.on(button,"click",function(){close(),me.focus()}),!1!==options.closeOnBlur&&CodeMirror.on(button,"blur",close),button.focus()),close}),CodeMirror.defineExtension("openConfirm",function(template,callbacks,options){function close(){closed||(closed=!0,dialog.parentNode.removeChild(dialog),me.focus())}closeNotification(this,null);var dialog=dialogDiv(this,template,options&&options.bottom),buttons=dialog.getElementsByTagName("button"),closed=!1,me=this,blurring=1;buttons[0].focus();for(var i=0;i<buttons.length;++i){var b=buttons[i];!function(callback){CodeMirror.on(b,"click",function(e){CodeMirror.e_preventDefault(e),close(),callback&&callback(me)})}(callbacks[i]),CodeMirror.on(b,"blur",function(){--blurring,setTimeout(function(){blurring<=0&&close()},200)}),CodeMirror.on(b,"focus",function(){++blurring})}}),CodeMirror.defineExtension("openNotification",function(template,options){function close(){closed||(closed=!0,clearTimeout(doneTimer),dialog.parentNode.removeChild(dialog))}closeNotification(this,close);var doneTimer,dialog=dialogDiv(this,template,options&&options.bottom),closed=!1,duration=options&&void 0!==options.duration?options.duration:5e3;return CodeMirror.on(dialog,"click",function(e){CodeMirror.e_preventDefault(e),close()}),duration&&(doneTimer=setTimeout(close,duration)),close})})},{"../../lib/codemirror":63}],53:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){function getOption(conf,name){return"pairs"==name&&"string"==typeof conf?conf:"object"==typeof conf&&null!=conf[name]?conf[name]:defaults[name]}function getConfig(cm){var deflt=cm.state.closeBrackets;return!deflt||deflt.override?deflt:cm.getModeAt(cm.getCursor()).closeBrackets||deflt}function contractSelection(sel){var inverted=CodeMirror.cmpPos(sel.anchor,sel.head)>0;return{anchor:new Pos(sel.anchor.line,sel.anchor.ch+(inverted?-1:1)),head:new Pos(sel.head.line,sel.head.ch+(inverted?1:-1))}}function handleChar(cm,ch){var conf=getConfig(cm);if(!conf||cm.getOption("disableInput"))return CodeMirror.Pass;var pairs=getOption(conf,"pairs"),pos=pairs.indexOf(ch);if(-1==pos)return CodeMirror.Pass;for(var type,triples=getOption(conf,"triples"),identical=pairs.charAt(pos+1)==ch,ranges=cm.listSelections(),opening=pos%2==0,i=0;i<ranges.length;i++){var curType,range=ranges[i],cur=range.head,next=cm.getRange(cur,Pos(cur.line,cur.ch+1));if(opening&&!range.empty())curType="surround";else if(!identical&&opening||next!=ch)if(identical&&cur.ch>1&&triples.indexOf(ch)>=0&&cm.getRange(Pos(cur.line,cur.ch-2),cur)==ch+ch&&(cur.ch<=2||cm.getRange(Pos(cur.line,cur.ch-3),Pos(cur.line,cur.ch-2))!=ch))curType="addFour";else if(identical){if(CodeMirror.isWordChar(next)||!enteringString(cm,cur,ch))return CodeMirror.Pass;curType="both"}else{if(!opening||cm.getLine(cur.line).length!=cur.ch&&!isClosingBracket(next,pairs)&&!/\s/.test(next))return CodeMirror.Pass;curType="both"}else curType=identical&&stringStartsAfter(cm,cur)?"both":triples.indexOf(ch)>=0&&cm.getRange(cur,Pos(cur.line,cur.ch+3))==ch+ch+ch?"skipThree":"skip";if(type){if(type!=curType)return CodeMirror.Pass}else type=curType}var left=pos%2?pairs.charAt(pos-1):ch,right=pos%2?ch:pairs.charAt(pos+1);cm.operation(function(){if("skip"==type)cm.execCommand("goCharRight");else if("skipThree"==type)for(i=0;i<3;i++)cm.execCommand("goCharRight");else if("surround"==type){for(var sels=cm.getSelections(),i=0;i<sels.length;i++)sels[i]=left+sels[i]+right;cm.replaceSelections(sels,"around"),sels=cm.listSelections().slice();for(i=0;i<sels.length;i++)sels[i]=contractSelection(sels[i]);cm.setSelections(sels)}else"both"==type?(cm.replaceSelection(left+right,null),cm.triggerElectric(left+right),cm.execCommand("goCharLeft")):"addFour"==type&&(cm.replaceSelection(left+left+left+left,"before"),cm.execCommand("goCharRight"))})}function isClosingBracket(ch,pairs){var pos=pairs.lastIndexOf(ch);return pos>-1&&pos%2==1}function charsAround(cm,pos){var str=cm.getRange(Pos(pos.line,pos.ch-1),Pos(pos.line,pos.ch+1));return 2==str.length?str:null}function enteringString(cm,pos,ch){var line=cm.getLine(pos.line),token=cm.getTokenAt(pos);if(/\bstring2?\b/.test(token.type)||stringStartsAfter(cm,pos))return!1;var stream=new CodeMirror.StringStream(line.slice(0,pos.ch)+ch+line.slice(pos.ch),4);for(stream.pos=stream.start=token.start;;){var type1=cm.getMode().token(stream,token.state);if(stream.pos>=pos.ch+1)return/\bstring2?\b/.test(type1);stream.start=stream.pos}}function stringStartsAfter(cm,pos){var token=cm.getTokenAt(Pos(pos.line,pos.ch+1));return/\bstring/.test(token.type)&&token.start==pos.ch}var defaults={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"},Pos=CodeMirror.Pos;CodeMirror.defineOption("autoCloseBrackets",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.removeKeyMap(keyMap),cm.state.closeBrackets=null),val&&(cm.state.closeBrackets=val,cm.addKeyMap(keyMap))});for(var bind=defaults.pairs+"`",keyMap={Backspace:function(cm){var conf=getConfig(cm);if(!conf||cm.getOption("disableInput"))return CodeMirror.Pass;for(var pairs=getOption(conf,"pairs"),ranges=cm.listSelections(),i=0;i<ranges.length;i++){if(!ranges[i].empty())return CodeMirror.Pass;var around=charsAround(cm,ranges[i].head);if(!around||pairs.indexOf(around)%2!=0)return CodeMirror.Pass}for(i=ranges.length-1;i>=0;i--){var cur=ranges[i].head;cm.replaceRange("",Pos(cur.line,cur.ch-1),Pos(cur.line,cur.ch+1),"+delete")}},Enter:function(cm){var conf=getConfig(cm),explode=conf&&getOption(conf,"explode");if(!explode||cm.getOption("disableInput"))return CodeMirror.Pass;for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++){if(!ranges[i].empty())return CodeMirror.Pass;var around=charsAround(cm,ranges[i].head);if(!around||explode.indexOf(around)%2!=0)return CodeMirror.Pass}cm.operation(function(){cm.replaceSelection("\n\n",null),cm.execCommand("goCharLeft"),ranges=cm.listSelections();for(var i=0;i<ranges.length;i++){var line=ranges[i].head.line;cm.indentLine(line,null,!0),cm.indentLine(line+1,null,!0)}})}},i=0;i<bind.length;i++)keyMap["'"+bind.charAt(i)+"'"]=function(ch){return function(cm){return handleChar(cm,ch)}}(bind.charAt(i))})},{"../../lib/codemirror":63}],54:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){function findMatchingBracket(cm,where,config){var line=cm.getLineHandle(where.line),pos=where.ch-1,afterCursor=config&&config.afterCursor;null==afterCursor&&(afterCursor=/(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className));var match=!afterCursor&&pos>=0&&matching[line.text.charAt(pos)]||matching[line.text.charAt(++pos)];if(!match)return null;var dir=">"==match.charAt(1)?1:-1;if(config&&config.strict&&dir>0!=(pos==where.ch))return null;var style=cm.getTokenTypeAt(Pos(where.line,pos+1)),found=scanForBracket(cm,Pos(where.line,pos+(dir>0?1:0)),dir,style||null,config);return null==found?null:{from:Pos(where.line,pos),to:found&&found.pos,match:found&&found.ch==match.charAt(0),forward:dir>0}}function scanForBracket(cm,where,dir,style,config){for(var maxScanLen=config&&config.maxScanLineLength||1e4,maxScanLines=config&&config.maxScanLines||1e3,stack=[],re=config&&config.bracketRegex?config.bracketRegex:/[(){}[\]]/,lineEnd=dir>0?Math.min(where.line+maxScanLines,cm.lastLine()+1):Math.max(cm.firstLine()-1,where.line-maxScanLines),lineNo=where.line;lineNo!=lineEnd;lineNo+=dir){var line=cm.getLine(lineNo);if(line){var pos=dir>0?0:line.length-1,end=dir>0?line.length:-1;if(!(line.length>maxScanLen))for(lineNo==where.line&&(pos=where.ch-(dir<0?1:0));pos!=end;pos+=dir){var ch=line.charAt(pos);if(re.test(ch)&&(void 0===style||cm.getTokenTypeAt(Pos(lineNo,pos+1))==style))if(">"==matching[ch].charAt(1)==dir>0)stack.push(ch);else{if(!stack.length)return{pos:Pos(lineNo,pos),ch:ch};stack.pop()}}}}return lineNo-dir!=(dir>0?cm.lastLine():cm.firstLine())&&null}function matchBrackets(cm,autoclear,config){for(var maxHighlightLen=cm.state.matchBrackets.maxHighlightLineLength||1e3,marks=[],ranges=cm.listSelections(),i=0;i<ranges.length;i++){var match=ranges[i].empty()&&findMatchingBracket(cm,ranges[i].head,config);if(match&&cm.getLine(match.from.line).length<=maxHighlightLen){var style=match.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";marks.push(cm.markText(match.from,Pos(match.from.line,match.from.ch+1),{className:style})),match.to&&cm.getLine(match.to.line).length<=maxHighlightLen&&marks.push(cm.markText(match.to,Pos(match.to.line,match.to.ch+1),{className:style}))}}if(marks.length){ie_lt8&&cm.state.focused&&cm.focus();var clear=function(){cm.operation(function(){for(var i=0;i<marks.length;i++)marks[i].clear()})};if(!autoclear)return clear;setTimeout(clear,800)}}function doMatchBrackets(cm){cm.operation(function(){currentlyHighlighted&&(currentlyHighlighted(),currentlyHighlighted=null),currentlyHighlighted=matchBrackets(cm,!1,cm.state.matchBrackets)})}var ie_lt8=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),Pos=CodeMirror.Pos,matching={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},currentlyHighlighted=null;CodeMirror.defineOption("matchBrackets",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.off("cursorActivity",doMatchBrackets),currentlyHighlighted&&(currentlyHighlighted(),currentlyHighlighted=null)),val&&(cm.state.matchBrackets="object"==typeof val?val:{},cm.on("cursorActivity",doMatchBrackets))}),CodeMirror.defineExtension("matchBrackets",function(){matchBrackets(this,!0)}),CodeMirror.defineExtension("findMatchingBracket",function(pos,config,oldConfig){return(oldConfig||"boolean"==typeof config)&&(oldConfig?(oldConfig.strict=config,config=oldConfig):config=config?{strict:!0}:null),findMatchingBracket(this,pos,config)}),CodeMirror.defineExtension("scanForBracket",function(pos,dir,style,config){return scanForBracket(this,pos,dir,style,config)})})},{"../../lib/codemirror":63}],55:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){"use strict";CodeMirror.registerHelper("fold","brace",function(cm,start){function findOpening(openCh){for(var at=start.ch,pass=0;;){var found=at<=0?-1:lineText.lastIndexOf(openCh,at-1);if(-1!=found){if(1==pass&&found<start.ch)break;if(tokenType=cm.getTokenTypeAt(CodeMirror.Pos(line,found+1)),!/^(comment|string)/.test(tokenType))return found+1;at=found-1}else{if(1==pass)break;pass=1,at=lineText.length}}}var tokenType,line=start.line,lineText=cm.getLine(line),startToken="{",endToken="}",startCh=findOpening("{");if(null==startCh&&(startToken="[",endToken="]",startCh=findOpening("[")),null!=startCh){var end,endCh,count=1,lastLine=cm.lastLine();outer:for(var i=line;i<=lastLine;++i)for(var text=cm.getLine(i),pos=i==line?startCh:0;;){var nextOpen=text.indexOf(startToken,pos),nextClose=text.indexOf(endToken,pos);if(nextOpen<0&&(nextOpen=text.length),nextClose<0&&(nextClose=text.length),(pos=Math.min(nextOpen,nextClose))==text.length)break;if(cm.getTokenTypeAt(CodeMirror.Pos(i,pos+1))==tokenType)if(pos==nextOpen)++count;else if(!--count){end=i,endCh=pos;break outer}++pos}if(null!=end&&(line!=end||endCh!=startCh))return{from:CodeMirror.Pos(line,startCh),to:CodeMirror.Pos(end,endCh)}}}),CodeMirror.registerHelper("fold","import",function(cm,start){function hasImport(line){if(line<cm.firstLine()||line>cm.lastLine())return null;var start=cm.getTokenAt(CodeMirror.Pos(line,1));if(/\S/.test(start.string)||(start=cm.getTokenAt(CodeMirror.Pos(line,start.end+1))),"keyword"!=start.type||"import"!=start.string)return null;for(var i=line,e=Math.min(cm.lastLine(),line+10);i<=e;++i){var semi=cm.getLine(i).indexOf(";");if(-1!=semi)return{startCh:start.end,end:CodeMirror.Pos(i,semi)}}}var prev,startLine=start.line,has=hasImport(startLine);if(!has||hasImport(startLine-1)||(prev=hasImport(startLine-2))&&prev.end.line==startLine-1)return null;for(var end=has.end;;){var next=hasImport(end.line+1);if(null==next)break;end=next.end}return{from:cm.clipPos(CodeMirror.Pos(startLine,has.startCh+1)),to:end}}),CodeMirror.registerHelper("fold","include",function(cm,start){function hasInclude(line){if(line<cm.firstLine()||line>cm.lastLine())return null;var start=cm.getTokenAt(CodeMirror.Pos(line,1));return/\S/.test(start.string)||(start=cm.getTokenAt(CodeMirror.Pos(line,start.end+1))),"meta"==start.type&&"#include"==start.string.slice(0,8)?start.start+8:void 0}var startLine=start.line,has=hasInclude(startLine);if(null==has||null!=hasInclude(startLine-1))return null;for(var end=startLine;null!=hasInclude(end+1);)++end;return{from:CodeMirror.Pos(startLine,has+1),to:cm.clipPos(CodeMirror.Pos(end))}})})},{"../../lib/codemirror":63}],56:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){"use strict";function doFold(cm,pos,options,force){function getRange(allowFolded){var range=finder(cm,pos);if(!range||range.to.line-range.from.line<minSize)return null;for(var marks=cm.findMarksAt(range.from),i=0;i<marks.length;++i)if(marks[i].__isFold&&"fold"!==force){if(!allowFolded)return null;range.cleared=!0,marks[i].clear()}return range}if(options&&options.call){finder=options;options=null}else var finder=getOption(cm,options,"rangeFinder");"number"==typeof pos&&(pos=CodeMirror.Pos(pos,0));var minSize=getOption(cm,options,"minFoldSize"),range=getRange(!0);if(getOption(cm,options,"scanUp"))for(;!range&&pos.line>cm.firstLine();)pos=CodeMirror.Pos(pos.line-1,0),range=getRange(!1);if(range&&!range.cleared&&"unfold"!==force){var myWidget=makeWidget(cm,options);CodeMirror.on(myWidget,"mousedown",function(e){myRange.clear(),CodeMirror.e_preventDefault(e)});var myRange=cm.markText(range.from,range.to,{replacedWith:myWidget,clearOnEnter:getOption(cm,options,"clearOnEnter"),__isFold:!0});myRange.on("clear",function(from,to){CodeMirror.signal(cm,"unfold",cm,from,to)}),CodeMirror.signal(cm,"fold",cm,range.from,range.to)}}function makeWidget(cm,options){var widget=getOption(cm,options,"widget");if("string"==typeof widget){var text=document.createTextNode(widget);(widget=document.createElement("span")).appendChild(text),widget.className="CodeMirror-foldmarker"}return widget}function getOption(cm,options,name){if(options&&void 0!==options[name])return options[name];var editorOptions=cm.options.foldOptions;return editorOptions&&void 0!==editorOptions[name]?editorOptions[name]:defaultOptions[name]}CodeMirror.newFoldFunction=function(rangeFinder,widget){return function(cm,pos){doFold(cm,pos,{rangeFinder:rangeFinder,widget:widget})}},CodeMirror.defineExtension("foldCode",function(pos,options,force){doFold(this,pos,options,force)}),CodeMirror.defineExtension("isFolded",function(pos){for(var marks=this.findMarksAt(pos),i=0;i<marks.length;++i)if(marks[i].__isFold)return!0}),CodeMirror.commands.toggleFold=function(cm){cm.foldCode(cm.getCursor())},CodeMirror.commands.fold=function(cm){cm.foldCode(cm.getCursor(),null,"fold")},CodeMirror.commands.unfold=function(cm){cm.foldCode(cm.getCursor(),null,"unfold")},CodeMirror.commands.foldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)cm.foldCode(CodeMirror.Pos(i,0),null,"fold")})},CodeMirror.commands.unfoldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)cm.foldCode(CodeMirror.Pos(i,0),null,"unfold")})},CodeMirror.registerHelper("fold","combine",function(){var funcs=Array.prototype.slice.call(arguments,0);return function(cm,start){for(var i=0;i<funcs.length;++i){var found=funcs[i](cm,start);if(found)return found}}}),CodeMirror.registerHelper("fold","auto",function(cm,start){for(var helpers=cm.getHelpers(start,"fold"),i=0;i<helpers.length;i++){var cur=helpers[i](cm,start);if(cur)return cur}});var defaultOptions={rangeFinder:CodeMirror.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1,clearOnEnter:!0};CodeMirror.defineOption("foldOptions",null),CodeMirror.defineExtension("foldOption",function(options,name){return getOption(this,options,name)})})},{"../../lib/codemirror":63}],57:[function(require,module,exports){!function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./foldcode")):mod(CodeMirror)}(function(CodeMirror){"use strict";function State(options){this.options=options,this.from=this.to=0}function parseOptions(opts){return!0===opts&&(opts={}),null==opts.gutter&&(opts.gutter="CodeMirror-foldgutter"),null==opts.indicatorOpen&&(opts.indicatorOpen="CodeMirror-foldgutter-open"),null==opts.indicatorFolded&&(opts.indicatorFolded="CodeMirror-foldgutter-folded"),opts}function isFolded(cm,line){for(var marks=cm.findMarks(Pos(line,0),Pos(line+1,0)),i=0;i<marks.length;++i)if(marks[i].__isFold&&marks[i].find().from.line==line)return marks[i]}function marker(spec){if("string"==typeof spec){var elt=document.createElement("div");return elt.className=spec+" CodeMirror-guttermarker-subtle",elt}return spec.cloneNode(!0)}function updateFoldInfo(cm,from,to){var opts=cm.state.foldGutter.options,cur=from,minSize=cm.foldOption(opts,"minFoldSize"),func=cm.foldOption(opts,"rangeFinder");cm.eachLine(from,to,function(line){var mark=null;if(isFolded(cm,cur))mark=marker(opts.indicatorFolded);else{var pos=Pos(cur,0),range=func&&func(cm,pos);range&&range.to.line-range.from.line>=minSize&&(mark=marker(opts.indicatorOpen))}cm.setGutterMarker(line,opts.gutter,mark),++cur})}function updateInViewport(cm){var vp=cm.getViewport(),state=cm.state.foldGutter;state&&(cm.operation(function(){updateFoldInfo(cm,vp.from,vp.to)}),state.from=vp.from,state.to=vp.to)}function onGutterClick(cm,line,gutter){var state=cm.state.foldGutter;if(state){var opts=state.options;if(gutter==opts.gutter){var folded=isFolded(cm,line);folded?folded.clear():cm.foldCode(Pos(line,0),opts.rangeFinder)}}}function onChange(cm){var state=cm.state.foldGutter;if(state){var opts=state.options;state.from=state.to=0,clearTimeout(state.changeUpdate),state.changeUpdate=setTimeout(function(){updateInViewport(cm)},opts.foldOnChangeTimeSpan||600)}}function onViewportChange(cm){var state=cm.state.foldGutter;if(state){var opts=state.options;clearTimeout(state.changeUpdate),state.changeUpdate=setTimeout(function(){var vp=cm.getViewport();state.from==state.to||vp.from-state.to>20||state.from-vp.to>20?updateInViewport(cm):cm.operation(function(){vp.from<state.from&&(updateFoldInfo(cm,vp.from,state.from),state.from=vp.from),vp.to>state.to&&(updateFoldInfo(cm,state.to,vp.to),state.to=vp.to)})},opts.updateViewportTimeSpan||400)}}function onFold(cm,from){var state=cm.state.foldGutter;if(state){var line=from.line;line>=state.from&&line<state.to&&updateFoldInfo(cm,line,line+1)}}CodeMirror.defineOption("foldGutter",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.clearGutter(cm.state.foldGutter.options.gutter),cm.state.foldGutter=null,cm.off("gutterClick",onGutterClick),cm.off("change",onChange),cm.off("viewportChange",onViewportChange),cm.off("fold",onFold),cm.off("unfold",onFold),cm.off("swapDoc",onChange)),val&&(cm.state.foldGutter=new State(parseOptions(val)),updateInViewport(cm),cm.on("gutterClick",onGutterClick),cm.on("change",onChange),cm.on("viewportChange",onViewportChange),cm.on("fold",onFold),cm.on("unfold",onFold),cm.on("swapDoc",onChange))});var Pos=CodeMirror.Pos})},{"../../lib/codemirror":63,"./foldcode":56}],58:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){"use strict";function Completion(cm,options){this.cm=cm,this.options=options,this.widget=null,this.debounce=0,this.tick=0,this.startPos=this.cm.getCursor("start"),this.startLen=this.cm.getLine(this.startPos.line).length-this.cm.getSelection().length;var self=this;cm.on("cursorActivity",this.activityFunc=function(){self.cursorActivity()})}function isNewCompletion(old,nw){return CodeMirror.cmpPos(nw.from,old.from)>0&&old.to.ch-old.from.ch!=nw.to.ch-nw.from.ch}function parseOptions(cm,pos,options){var editor=cm.options.hintOptions,out={};for(var prop in defaultOptions)out[prop]=defaultOptions[prop];if(editor)for(var prop in editor)void 0!==editor[prop]&&(out[prop]=editor[prop]);if(options)for(var prop in options)void 0!==options[prop]&&(out[prop]=options[prop]);return out.hint.resolve&&(out.hint=out.hint.resolve(cm,pos)),out}function getText(completion){return"string"==typeof completion?completion:completion.text}function buildKeyMap(completion,handle){function addBinding(key,val){var bound;bound="string"!=typeof val?function(cm){return val(cm,handle)}:baseMap.hasOwnProperty(val)?baseMap[val]:val,ourMap[key]=bound}var baseMap={Up:function(){handle.moveFocus(-1)},Down:function(){handle.moveFocus(1)},PageUp:function(){handle.moveFocus(1-handle.menuSize(),!0)},PageDown:function(){handle.moveFocus(handle.menuSize()-1,!0)},Home:function(){handle.setFocus(0)},End:function(){handle.setFocus(handle.length-1)},Enter:handle.pick,Tab:handle.pick,Esc:handle.close},custom=completion.options.customKeys,ourMap=custom?{}:baseMap;if(custom)for(var key in custom)custom.hasOwnProperty(key)&&addBinding(key,custom[key]);var extra=completion.options.extraKeys;if(extra)for(var key in extra)extra.hasOwnProperty(key)&&addBinding(key,extra[key]);return ourMap}function getHintElement(hintsElement,el){for(;el&&el!=hintsElement;){if("LI"===el.nodeName.toUpperCase()&&el.parentNode==hintsElement)return el;el=el.parentNode}}function Widget(completion,data){this.completion=completion,this.data=data,this.picked=!1;var widget=this,cm=completion.cm,hints=this.hints=document.createElement("ul");hints.className="CodeMirror-hints",this.selectedHint=data.selectedHint||0;for(var completions=data.list,i=0;i<completions.length;++i){var elt=hints.appendChild(document.createElement("li")),cur=completions[i],className=HINT_ELEMENT_CLASS+(i!=this.selectedHint?"":" "+ACTIVE_HINT_ELEMENT_CLASS);null!=cur.className&&(className=cur.className+" "+className),elt.className=className,cur.render?cur.render(elt,data,cur):elt.appendChild(document.createTextNode(cur.displayText||getText(cur))),elt.hintId=i}var pos=cm.cursorCoords(completion.options.alignWithWord?data.from:null),left=pos.left,top=pos.bottom,below=!0;hints.style.left=left+"px",hints.style.top=top+"px";var winW=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),winH=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(completion.options.container||document.body).appendChild(hints);var box=hints.getBoundingClientRect(),overlapY=box.bottom-winH,scrolls=hints.scrollHeight>hints.clientHeight+1,startScroll=cm.getScrollInfo();if(overlapY>0){var height=box.bottom-box.top;if(pos.top-(pos.bottom-box.top)-height>0)hints.style.top=(top=pos.top-height)+"px",below=!1;else if(height>winH){hints.style.height=winH-5+"px",hints.style.top=(top=pos.bottom-box.top)+"px";var cursor=cm.getCursor();data.from.ch!=cursor.ch&&(pos=cm.cursorCoords(cursor),hints.style.left=(left=pos.left)+"px",box=hints.getBoundingClientRect())}}var overlapX=box.right-winW;if(overlapX>0&&(box.right-box.left>winW&&(hints.style.width=winW-5+"px",overlapX-=box.right-box.left-winW),hints.style.left=(left=pos.left-overlapX)+"px"),scrolls)for(var node=hints.firstChild;node;node=node.nextSibling)node.style.paddingRight=cm.display.nativeBarWidth+"px";if(cm.addKeyMap(this.keyMap=buildKeyMap(completion,{moveFocus:function(n,avoidWrap){widget.changeActive(widget.selectedHint+n,avoidWrap)},setFocus:function(n){widget.changeActive(n)},menuSize:function(){return widget.screenAmount()},length:completions.length,close:function(){completion.close()},pick:function(){widget.pick()},data:data})),completion.options.closeOnUnfocus){var closingOnBlur;cm.on("blur",this.onBlur=function(){closingOnBlur=setTimeout(function(){completion.close()},100)}),cm.on("focus",this.onFocus=function(){clearTimeout(closingOnBlur)})}return cm.on("scroll",this.onScroll=function(){var curScroll=cm.getScrollInfo(),editor=cm.getWrapperElement().getBoundingClientRect(),newTop=top+startScroll.top-curScroll.top,point=newTop-(window.pageYOffset||(document.documentElement||document.body).scrollTop);if(below||(point+=hints.offsetHeight),point<=editor.top||point>=editor.bottom)return completion.close();hints.style.top=newTop+"px",hints.style.left=left+startScroll.left-curScroll.left+"px"}),CodeMirror.on(hints,"dblclick",function(e){var t=getHintElement(hints,e.target||e.srcElement);t&&null!=t.hintId&&(widget.changeActive(t.hintId),widget.pick())}),CodeMirror.on(hints,"click",function(e){var t=getHintElement(hints,e.target||e.srcElement);t&&null!=t.hintId&&(widget.changeActive(t.hintId),completion.options.completeOnSingleClick&&widget.pick())}),CodeMirror.on(hints,"mousedown",function(){setTimeout(function(){cm.focus()},20)}),CodeMirror.signal(data,"select",completions[0],hints.firstChild),!0}function applicableHelpers(cm,helpers){if(!cm.somethingSelected())return helpers;for(var result=[],i=0;i<helpers.length;i++)helpers[i].supportsSelection&&result.push(helpers[i]);return result}function fetchHints(hint,cm,options,callback){if(hint.async)hint(cm,callback,options);else{var result=hint(cm,options);result&&result.then?result.then(callback):callback(result)}}var HINT_ELEMENT_CLASS="CodeMirror-hint",ACTIVE_HINT_ELEMENT_CLASS="CodeMirror-hint-active";CodeMirror.showHint=function(cm,getHints,options){if(!getHints)return cm.showHint(options);options&&options.async&&(getHints.async=!0);var newOpts={hint:getHints};if(options)for(var prop in options)newOpts[prop]=options[prop];return cm.showHint(newOpts)},CodeMirror.defineExtension("showHint",function(options){options=parseOptions(this,this.getCursor("start"),options);var selections=this.listSelections();if(!(selections.length>1)){if(this.somethingSelected()){if(!options.hint.supportsSelection)return;for(var i=0;i<selections.length;i++)if(selections[i].head.line!=selections[i].anchor.line)return}this.state.completionActive&&this.state.completionActive.close();var completion=this.state.completionActive=new Completion(this,options);completion.options.hint&&(CodeMirror.signal(this,"startCompletion",this),completion.update(!0))}});var requestAnimationFrame=window.requestAnimationFrame||function(fn){return setTimeout(fn,1e3/60)},cancelAnimationFrame=window.cancelAnimationFrame||clearTimeout;Completion.prototype={close:function(){this.active()&&(this.cm.state.completionActive=null,this.tick=null,this.cm.off("cursorActivity",this.activityFunc),this.widget&&this.data&&CodeMirror.signal(this.data,"close"),this.widget&&this.widget.close(),CodeMirror.signal(this.cm,"endCompletion",this.cm))},active:function(){return this.cm.state.completionActive==this},pick:function(data,i){var completion=data.list[i];completion.hint?completion.hint(this.cm,data,completion):this.cm.replaceRange(getText(completion),completion.from||data.from,completion.to||data.to,"complete"),CodeMirror.signal(data,"pick",completion),this.close()},cursorActivity:function(){this.debounce&&(cancelAnimationFrame(this.debounce),this.debounce=0);var pos=this.cm.getCursor(),line=this.cm.getLine(pos.line);if(pos.line!=this.startPos.line||line.length-pos.ch!=this.startLen-this.startPos.ch||pos.ch<this.startPos.ch||this.cm.somethingSelected()||pos.ch&&this.options.closeCharacters.test(line.charAt(pos.ch-1)))this.close();else{var self=this;this.debounce=requestAnimationFrame(function(){self.update()}),this.widget&&this.widget.disable()}},update:function(first){if(null!=this.tick){var self=this,myTick=++this.tick;fetchHints(this.options.hint,this.cm,this.options,function(data){self.tick==myTick&&self.finishUpdate(data,first)})}},finishUpdate:function(data,first){this.data&&CodeMirror.signal(this.data,"update");var picked=this.widget&&this.widget.picked||first&&this.options.completeSingle;this.widget&&this.widget.close(),data&&this.data&&isNewCompletion(this.data,data)||(this.data=data,data&&data.list.length&&(picked&&1==data.list.length?this.pick(data,0):(this.widget=new Widget(this,data),CodeMirror.signal(data,"shown"))))}},Widget.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null,this.hints.parentNode.removeChild(this.hints),this.completion.cm.removeKeyMap(this.keyMap);var cm=this.completion.cm;this.completion.options.closeOnUnfocus&&(cm.off("blur",this.onBlur),cm.off("focus",this.onFocus)),cm.off("scroll",this.onScroll)}},disable:function(){this.completion.cm.removeKeyMap(this.keyMap);var widget=this;this.keyMap={Enter:function(){widget.picked=!0}},this.completion.cm.addKeyMap(this.keyMap)},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(i,avoidWrap){if(i>=this.data.list.length?i=avoidWrap?this.data.list.length-1:0:i<0&&(i=avoidWrap?0:this.data.list.length-1),this.selectedHint!=i){var node=this.hints.childNodes[this.selectedHint];node.className=node.className.replace(" "+ACTIVE_HINT_ELEMENT_CLASS,""),(node=this.hints.childNodes[this.selectedHint=i]).className+=" "+ACTIVE_HINT_ELEMENT_CLASS,node.offsetTop<this.hints.scrollTop?this.hints.scrollTop=node.offsetTop-3:node.offsetTop+node.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=node.offsetTop+node.offsetHeight-this.hints.clientHeight+3),CodeMirror.signal(this.data,"select",this.data.list[this.selectedHint],node)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},CodeMirror.registerHelper("hint","auto",{resolve:function(cm,pos){var words,helpers=cm.getHelpers(pos,"hint");if(helpers.length){var resolved=function(cm,callback,options){function run(i){if(i==app.length)return callback(null);fetchHints(app[i],cm,options,function(result){result&&result.list.length>0?callback(result):run(i+1)})}var app=applicableHelpers(cm,helpers);run(0)};return resolved.async=!0,resolved.supportsSelection=!0,resolved}return(words=cm.getHelper(cm.getCursor(),"hintWords"))?function(cm){return CodeMirror.hint.fromList(cm,{words:words})}:CodeMirror.hint.anyword?function(cm,options){return CodeMirror.hint.anyword(cm,options)}:function(){}}}),CodeMirror.registerHelper("hint","fromList",function(cm,options){var cur=cm.getCursor(),token=cm.getTokenAt(cur),to=CodeMirror.Pos(cur.line,token.end);if(token.string&&/\w/.test(token.string[token.string.length-1]))var term=token.string,from=CodeMirror.Pos(cur.line,token.start);else var term="",from=to;for(var found=[],i=0;i<options.words.length;i++){var word=options.words[i];word.slice(0,term.length)==term&&found.push(word)}if(found.length)return{list:found,from:from,to:to}}),CodeMirror.commands.autocomplete=CodeMirror.showHint;var defaultOptions={hint:CodeMirror.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null};CodeMirror.defineOption("hintOptions",null)})},{"../../lib/codemirror":63}],59:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){"use strict";function showTooltip(e,content){function position(e){if(!tt.parentNode)return CodeMirror.off(document,"mousemove",position);tt.style.top=Math.max(0,e.clientY-tt.offsetHeight-5)+"px",tt.style.left=e.clientX+5+"px"}var tt=document.createElement("div");return tt.className="CodeMirror-lint-tooltip",tt.appendChild(content.cloneNode(!0)),document.body.appendChild(tt),CodeMirror.on(document,"mousemove",position),position(e),null!=tt.style.opacity&&(tt.style.opacity=1),tt}function rm(elt){elt.parentNode&&elt.parentNode.removeChild(elt)}function hideTooltip(tt){tt.parentNode&&(null==tt.style.opacity&&rm(tt),tt.style.opacity=0,setTimeout(function(){rm(tt)},600))}function showTooltipFor(e,content,node){function hide(){CodeMirror.off(node,"mouseout",hide),tooltip&&(hideTooltip(tooltip),tooltip=null)}var tooltip=showTooltip(e,content),poll=setInterval(function(){if(tooltip)for(var n=node;;n=n.parentNode){if(n&&11==n.nodeType&&(n=n.host),n==document.body)return;if(!n){hide();break}}if(!tooltip)return clearInterval(poll)},400);CodeMirror.on(node,"mouseout",hide)}function LintState(cm,options,hasGutter){this.marked=[],this.options=options,this.timeout=null,this.hasGutter=hasGutter,this.onMouseOver=function(e){onMouseOver(cm,e)},this.waitingFor=0}function parseOptions(_cm,options){return options instanceof Function?{getAnnotations:options}:(options&&!0!==options||(options={}),options)}function clearMarks(cm){var state=cm.state.lint;state.hasGutter&&cm.clearGutter(GUTTER_ID);for(var i=0;i<state.marked.length;++i)state.marked[i].clear();state.marked.length=0}function makeMarker(labels,severity,multiple,tooltips){var marker=document.createElement("div"),inner=marker;return marker.className="CodeMirror-lint-marker-"+severity,multiple&&((inner=marker.appendChild(document.createElement("div"))).className="CodeMirror-lint-marker-multiple"),0!=tooltips&&CodeMirror.on(inner,"mouseover",function(e){showTooltipFor(e,labels,inner)}),marker}function getMaxSeverity(a,b){return"error"==a?a:b}function groupByLine(annotations){for(var lines=[],i=0;i<annotations.length;++i){var ann=annotations[i],line=ann.from.line;(lines[line]||(lines[line]=[])).push(ann)}return lines}function annotationTooltip(ann){var severity=ann.severity;severity||(severity="error");var tip=document.createElement("div");return tip.className="CodeMirror-lint-message-"+severity,tip.appendChild(document.createTextNode(ann.message)),tip}function lintAsync(cm,getAnnotations,passOptions){function abort(){id=-1,cm.off("change",abort)}var state=cm.state.lint,id=++state.waitingFor;cm.on("change",abort),getAnnotations(cm.getValue(),function(annotations,arg2){cm.off("change",abort),state.waitingFor==id&&(arg2&&annotations instanceof CodeMirror&&(annotations=arg2),updateLinting(cm,annotations))},passOptions,cm)}function startLinting(cm){var options=cm.state.lint.options,passOptions=options.options||options,getAnnotations=options.getAnnotations||cm.getHelper(CodeMirror.Pos(0,0),"lint");if(getAnnotations)if(options.async||getAnnotations.async)lintAsync(cm,getAnnotations,passOptions);else{var annotations=getAnnotations(cm.getValue(),passOptions,cm);if(!annotations)return;annotations.then?annotations.then(function(issues){updateLinting(cm,issues)}):updateLinting(cm,annotations)}}function updateLinting(cm,annotationsNotSorted){clearMarks(cm);for(var state=cm.state.lint,options=state.options,annotations=groupByLine(annotationsNotSorted),line=0;line<annotations.length;++line){var anns=annotations[line];if(anns){for(var maxSeverity=null,tipLabel=state.hasGutter&&document.createDocumentFragment(),i=0;i<anns.length;++i){var ann=anns[i],severity=ann.severity;severity||(severity="error"),maxSeverity=getMaxSeverity(maxSeverity,severity),options.formatAnnotation&&(ann=options.formatAnnotation(ann)),state.hasGutter&&tipLabel.appendChild(annotationTooltip(ann)),ann.to&&state.marked.push(cm.markText(ann.from,ann.to,{className:"CodeMirror-lint-mark-"+severity,__annotation:ann}))}state.hasGutter&&cm.setGutterMarker(line,GUTTER_ID,makeMarker(tipLabel,maxSeverity,anns.length>1,state.options.tooltips))}}options.onUpdateLinting&&options.onUpdateLinting(annotationsNotSorted,annotations,cm)}function onChange(cm){var state=cm.state.lint;state&&(clearTimeout(state.timeout),state.timeout=setTimeout(function(){startLinting(cm)},state.options.delay||500))}function popupTooltips(annotations,e){for(var target=e.target||e.srcElement,tooltip=document.createDocumentFragment(),i=0;i<annotations.length;i++){var ann=annotations[i];tooltip.appendChild(annotationTooltip(ann))}showTooltipFor(e,tooltip,target)}function onMouseOver(cm,e){var target=e.target||e.srcElement;if(/\bCodeMirror-lint-mark-/.test(target.className)){for(var box=target.getBoundingClientRect(),x=(box.left+box.right)/2,y=(box.top+box.bottom)/2,spans=cm.findMarksAt(cm.coordsChar({left:x,top:y},"client")),annotations=[],i=0;i<spans.length;++i){var ann=spans[i].__annotation;ann&&annotations.push(ann)}annotations.length&&popupTooltips(annotations,e)}}var GUTTER_ID="CodeMirror-lint-markers";CodeMirror.defineOption("lint",!1,function(cm,val,old){if(old&&old!=CodeMirror.Init&&(clearMarks(cm),!1!==cm.state.lint.options.lintOnChange&&cm.off("change",onChange),CodeMirror.off(cm.getWrapperElement(),"mouseover",cm.state.lint.onMouseOver),clearTimeout(cm.state.lint.timeout),delete cm.state.lint),val){for(var gutters=cm.getOption("gutters"),hasLintGutter=!1,i=0;i<gutters.length;++i)gutters[i]==GUTTER_ID&&(hasLintGutter=!0);var state=cm.state.lint=new LintState(cm,parseOptions(0,val),hasLintGutter);!1!==state.options.lintOnChange&&cm.on("change",onChange),0!=state.options.tooltips&&"gutter"!=state.options.tooltips&&CodeMirror.on(cm.getWrapperElement(),"mouseover",state.onMouseOver),startLinting(cm)}}),CodeMirror.defineExtension("performLint",function(){this.state.lint&&startLinting(this)})})},{"../../lib/codemirror":63}],60:[function(require,module,exports){!function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./searchcursor"),require("../dialog/dialog")):mod(CodeMirror)}(function(CodeMirror){"use strict";function searchOverlay(query,caseInsensitive){return"string"==typeof query?query=new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),caseInsensitive?"gi":"g"):query.global||(query=new RegExp(query.source,query.ignoreCase?"gi":"g")),{token:function(stream){query.lastIndex=stream.pos;var match=query.exec(stream.string);if(match&&match.index==stream.pos)return stream.pos+=match[0].length||1,"searching";match?stream.pos=match.index:stream.skipToEnd()}}}function SearchState(){this.posFrom=this.posTo=this.lastQuery=this.query=null,this.overlay=null}function getSearchState(cm){return cm.state.search||(cm.state.search=new SearchState)}function queryCaseInsensitive(query){return"string"==typeof query&&query==query.toLowerCase()}function getSearchCursor(cm,query,pos){return cm.getSearchCursor(query,pos,{caseFold:queryCaseInsensitive(query),multiline:!0})}function persistentDialog(cm,text,deflt,onEnter,onKeyDown){cm.openDialog(text,onEnter,{value:deflt,selectValueOnOpen:!0,closeOnEnter:!1,onClose:function(){clearSearch(cm)},onKeyDown:onKeyDown})}function dialog(cm,text,shortText,deflt,f){cm.openDialog?cm.openDialog(text,f,{value:deflt,selectValueOnOpen:!0}):f(prompt(shortText,deflt))}function confirmDialog(cm,text,shortText,fs){cm.openConfirm?cm.openConfirm(text,fs):confirm(shortText)&&fs[0]()}function parseString(string){return string.replace(/\\(.)/g,function(_,ch){return"n"==ch?"\n":"r"==ch?"\r":ch})}function parseQuery(query){var isRE=query.match(/^\/(.*)\/([a-z]*)$/);if(isRE)try{query=new RegExp(isRE[1],-1==isRE[2].indexOf("i")?"":"i")}catch(e){}else query=parseString(query);return("string"==typeof query?""==query:query.test(""))&&(query=/x^/),query}function startSearch(cm,state,query){state.queryText=query,state.query=parseQuery(query),cm.removeOverlay(state.overlay,queryCaseInsensitive(state.query)),state.overlay=searchOverlay(state.query,queryCaseInsensitive(state.query)),cm.addOverlay(state.overlay),cm.showMatchesOnScrollbar&&(state.annotate&&(state.annotate.clear(),state.annotate=null),state.annotate=cm.showMatchesOnScrollbar(state.query,queryCaseInsensitive(state.query)))}function doSearch(cm,rev,persistent,immediate){var state=getSearchState(cm);if(state.query)return findNext(cm,rev);var q=cm.getSelection()||state.lastQuery;if(persistent&&cm.openDialog){var hiding=null,searchNext=function(query,event){CodeMirror.e_stop(event),query&&(query!=state.queryText&&(startSearch(cm,state,query),state.posFrom=state.posTo=cm.getCursor()),hiding&&(hiding.style.opacity=1),findNext(cm,event.shiftKey,function(_,to){var dialog;to.line<3&&document.querySelector&&(dialog=cm.display.wrapper.querySelector(".CodeMirror-dialog"))&&dialog.getBoundingClientRect().bottom-4>cm.cursorCoords(to,"window").top&&((hiding=dialog).style.opacity=.4)}))};persistentDialog(cm,queryDialog,q,searchNext,function(event,query){var keyName=CodeMirror.keyName(event),cmd=CodeMirror.keyMap[cm.getOption("keyMap")][keyName];cmd||(cmd=cm.getOption("extraKeys")[keyName]),"findNext"==cmd||"findPrev"==cmd||"findPersistentNext"==cmd||"findPersistentPrev"==cmd?(CodeMirror.e_stop(event),startSearch(cm,getSearchState(cm),query),cm.execCommand(cmd)):"find"!=cmd&&"findPersistent"!=cmd||(CodeMirror.e_stop(event),searchNext(query,event))}),immediate&&q&&(startSearch(cm,state,q),findNext(cm,rev))}else dialog(cm,queryDialog,"Search for:",q,function(query){query&&!state.query&&cm.operation(function(){startSearch(cm,state,query),state.posFrom=state.posTo=cm.getCursor(),findNext(cm,rev)})})}function findNext(cm,rev,callback){cm.operation(function(){var state=getSearchState(cm),cursor=getSearchCursor(cm,state.query,rev?state.posFrom:state.posTo);(cursor.find(rev)||(cursor=getSearchCursor(cm,state.query,rev?CodeMirror.Pos(cm.lastLine()):CodeMirror.Pos(cm.firstLine(),0))).find(rev))&&(cm.setSelection(cursor.from(),cursor.to()),cm.scrollIntoView({from:cursor.from(),to:cursor.to()},20),state.posFrom=cursor.from(),state.posTo=cursor.to(),callback&&callback(cursor.from(),cursor.to()))})}function clearSearch(cm){cm.operation(function(){var state=getSearchState(cm);state.lastQuery=state.query,state.query&&(state.query=state.queryText=null,cm.removeOverlay(state.overlay),state.annotate&&(state.annotate.clear(),state.annotate=null))})}function replaceAll(cm,query,text){cm.operation(function(){for(var cursor=getSearchCursor(cm,query);cursor.findNext();)if("string"!=typeof query){var match=cm.getRange(cursor.from(),cursor.to()).match(query);cursor.replace(text.replace(/\$(\d)/g,function(_,i){return match[i]}))}else cursor.replace(text)})}function replace(cm,all){if(!cm.getOption("readOnly")){var query=cm.getSelection()||getSearchState(cm).lastQuery,dialogText='<span class="CodeMirror-search-label">'+(all?"Replace all:":"Replace:")+"</span>";dialog(cm,dialogText+replaceQueryDialog,dialogText,query,function(query){query&&(query=parseQuery(query),dialog(cm,replacementQueryDialog,"Replace with:","",function(text){if(text=parseString(text),all)replaceAll(cm,query,text);else{clearSearch(cm);var cursor=getSearchCursor(cm,query,cm.getCursor("from")),advance=function(){var match,start=cursor.from();!(match=cursor.findNext())&&(cursor=getSearchCursor(cm,query),!(match=cursor.findNext())||start&&cursor.from().line==start.line&&cursor.from().ch==start.ch)||(cm.setSelection(cursor.from(),cursor.to()),cm.scrollIntoView({from:cursor.from(),to:cursor.to()}),confirmDialog(cm,doReplaceConfirm,"Replace?",[function(){doReplace(match)},advance,function(){replaceAll(cm,query,text)}]))},doReplace=function(match){cursor.replace("string"==typeof query?text:text.replace(/\$(\d)/g,function(_,i){return match[i]})),advance()};advance()}}))})}}var queryDialog='<span class="CodeMirror-search-label">Search:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>',replaceQueryDialog=' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>',replacementQueryDialog='<span class="CodeMirror-search-label">With:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>',doReplaceConfirm='<span class="CodeMirror-search-label">Replace?</span> <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>';CodeMirror.commands.find=function(cm){clearSearch(cm),doSearch(cm)},CodeMirror.commands.findPersistent=function(cm){clearSearch(cm),doSearch(cm,!1,!0)},CodeMirror.commands.findPersistentNext=function(cm){doSearch(cm,!1,!0,!0)},CodeMirror.commands.findPersistentPrev=function(cm){doSearch(cm,!0,!0,!0)},CodeMirror.commands.findNext=doSearch,CodeMirror.commands.findPrev=function(cm){doSearch(cm,!0)},CodeMirror.commands.clearSearch=clearSearch,CodeMirror.commands.replace=replace,CodeMirror.commands.replaceAll=function(cm){replace(cm,!0)}})},{"../../lib/codemirror":63,"../dialog/dialog":52,"./searchcursor":61}],61:[function(require,module,exports){!function(mod){mod("object"==typeof exports&&"object"==typeof module?require("../../lib/codemirror"):CodeMirror)}(function(CodeMirror){"use strict";function regexpFlags(regexp){var flags=regexp.flags;return null!=flags?flags:(regexp.ignoreCase?"i":"")+(regexp.global?"g":"")+(regexp.multiline?"m":"")}function ensureGlobal(regexp){return regexp.global?regexp:new RegExp(regexp.source,regexpFlags(regexp)+"g")}function maybeMultiline(regexp){return/\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)}function searchRegexpForward(doc,regexp,start){regexp=ensureGlobal(regexp);for(var line=start.line,ch=start.ch,last=doc.lastLine();line<=last;line++,ch=0){regexp.lastIndex=ch;var string=doc.getLine(line),match=regexp.exec(string);if(match)return{from:Pos(line,match.index),to:Pos(line,match.index+match[0].length),match:match}}}function searchRegexpForwardMultiline(doc,regexp,start){if(!maybeMultiline(regexp))return searchRegexpForward(doc,regexp,start);regexp=ensureGlobal(regexp);for(var string,chunk=1,line=start.line,last=doc.lastLine();line<=last;){for(var i=0;i<chunk;i++){var curLine=doc.getLine(line++);string=null==string?curLine:string+"\n"+curLine}chunk*=2,regexp.lastIndex=start.ch;var match=regexp.exec(string);if(match){var before=string.slice(0,match.index).split("\n"),inside=match[0].split("\n"),startLine=start.line+before.length-1,startCh=before[before.length-1].length;return{from:Pos(startLine,startCh),to:Pos(startLine+inside.length-1,1==inside.length?startCh+inside[0].length:inside[inside.length-1].length),match:match}}}}function lastMatchIn(string,regexp){for(var match,cutOff=0;;){regexp.lastIndex=cutOff;var newMatch=regexp.exec(string);if(!newMatch)return match;if(match=newMatch,(cutOff=match.index+(match[0].length||1))==string.length)return match}}function searchRegexpBackward(doc,regexp,start){regexp=ensureGlobal(regexp);for(var line=start.line,ch=start.ch,first=doc.firstLine();line>=first;line--,ch=-1){var string=doc.getLine(line);ch>-1&&(string=string.slice(0,ch));var match=lastMatchIn(string,regexp);if(match)return{from:Pos(line,match.index),to:Pos(line,match.index+match[0].length),match:match}}}function searchRegexpBackwardMultiline(doc,regexp,start){regexp=ensureGlobal(regexp);for(var string,chunk=1,line=start.line,first=doc.firstLine();line>=first;){for(var i=0;i<chunk;i++){var curLine=doc.getLine(line--);string=null==string?curLine.slice(0,start.ch):curLine+"\n"+string}chunk*=2;var match=lastMatchIn(string,regexp);if(match){var before=string.slice(0,match.index).split("\n"),inside=match[0].split("\n"),startLine=line+before.length,startCh=before[before.length-1].length;return{from:Pos(startLine,startCh),to:Pos(startLine+inside.length-1,1==inside.length?startCh+inside[0].length:inside[inside.length-1].length),match:match}}}}function adjustPos(orig,folded,pos){if(orig.length==folded.length)return pos;for(var pos1=Math.min(pos,orig.length);;){var len1=orig.slice(0,pos1).toLowerCase().length;if(len1<pos)++pos1;else{if(!(len1>pos))return pos1;--pos1}}}function searchStringForward(doc,query,start,caseFold){if(!query.length)return null;var fold=caseFold?doFold:noFold,lines=fold(query).split(/\r|\n\r?/);search:for(var line=start.line,ch=start.ch,last=doc.lastLine()+1-lines.length;line<=last;line++,ch=0){var orig=doc.getLine(line).slice(ch),string=fold(orig);if(1==lines.length){var found=string.indexOf(lines[0]);if(-1==found)continue search;var start=adjustPos(orig,string,found)+ch;return{from:Pos(line,adjustPos(orig,string,found)+ch),to:Pos(line,adjustPos(orig,string,found+lines[0].length)+ch)}}var cutFrom=string.length-lines[0].length;if(string.slice(cutFrom)==lines[0]){for(var i=1;i<lines.length-1;i++)if(fold(doc.getLine(line+i))!=lines[i])continue search;var end=doc.getLine(line+lines.length-1),endString=fold(end),lastLine=lines[lines.length-1];if(end.slice(0,lastLine.length)==lastLine)return{from:Pos(line,adjustPos(orig,string,cutFrom)+ch),to:Pos(line+lines.length-1,adjustPos(end,endString,lastLine.length))}}}}function searchStringBackward(doc,query,start,caseFold){if(!query.length)return null;var fold=caseFold?doFold:noFold,lines=fold(query).split(/\r|\n\r?/);search:for(var line=start.line,ch=start.ch,first=doc.firstLine()-1+lines.length;line>=first;line--,ch=-1){var orig=doc.getLine(line);ch>-1&&(orig=orig.slice(0,ch));var string=fold(orig);if(1==lines.length){var found=string.lastIndexOf(lines[0]);if(-1==found)continue search;return{from:Pos(line,adjustPos(orig,string,found)),to:Pos(line,adjustPos(orig,string,found+lines[0].length))}}var lastLine=lines[lines.length-1];if(string.slice(0,lastLine.length)==lastLine){for(var i=1,start=line-lines.length+1;i<lines.length-1;i++)if(fold(doc.getLine(start+i))!=lines[i])continue search;var top=doc.getLine(line+1-lines.length),topString=fold(top);if(topString.slice(topString.length-lines[0].length)==lines[0])return{from:Pos(line+1-lines.length,adjustPos(top,topString,top.length-lines[0].length)),to:Pos(line,adjustPos(orig,string,lastLine.length))}}}}function SearchCursor(doc,query,pos,options){this.atOccurrence=!1,this.doc=doc,pos=pos?doc.clipPos(pos):Pos(0,0),this.pos={from:pos,to:pos};var caseFold;"object"==typeof options?caseFold=options.caseFold:(caseFold=options,options=null),"string"==typeof query?(null==caseFold&&(caseFold=!1),this.matches=function(reverse,pos){return(reverse?searchStringBackward:searchStringForward)(doc,query,pos,caseFold)}):(query=ensureGlobal(query),options&&!1===options.multiline?this.matches=function(reverse,pos){return(reverse?searchRegexpBackward:searchRegexpForward)(doc,query,pos)}:this.matches=function(reverse,pos){return(reverse?searchRegexpBackwardMultiline:searchRegexpForwardMultiline)(doc,query,pos)})}var doFold,noFold,Pos=CodeMirror.Pos;String.prototype.normalize?(doFold=function(str){return str.normalize("NFD").toLowerCase()},noFold=function(str){return str.normalize("NFD")}):(doFold=function(str){return str.toLowerCase()},noFold=function(str){return str}),SearchCursor.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(reverse){for(var result=this.matches(reverse,this.doc.clipPos(reverse?this.pos.from:this.pos.to));result&&0==CodeMirror.cmpPos(result.from,result.to);)reverse?result.from.ch?result.from=Pos(result.from.line,result.from.ch-1):result=result.from.line==this.doc.firstLine()?null:this.matches(reverse,this.doc.clipPos(Pos(result.from.line-1))):result.to.ch<this.doc.getLine(result.to.line).length?result.to=Pos(result.to.line,result.to.ch+1):result=result.to.line==this.doc.lastLine()?null:this.matches(reverse,Pos(result.to.line+1,0));if(result)return this.pos=result,this.atOccurrence=!0,this.pos.match||!0;var end=Pos(reverse?this.doc.firstLine():this.doc.lastLine()+1,0);return this.pos={from:end,to:end},this.atOccurrence=!1},from:function(){if(this.atOccurrence)return this.pos.from},to:function(){if(this.atOccurrence)return this.pos.to},replace:function(newText,origin){if(this.atOccurrence){var lines=CodeMirror.splitLines(newText);this.doc.replaceRange(lines,this.pos.from,this.pos.to,origin),this.pos.to=Pos(this.pos.from.line+lines.length-1,lines[lines.length-1].length+(1==lines.length?this.pos.from.ch:0))}}},CodeMirror.defineExtension("getSearchCursor",function(query,pos,caseFold){return new SearchCursor(this.doc,query,pos,caseFold)}),CodeMirror.defineDocExtension("getSearchCursor",function(query,pos,caseFold){return new SearchCursor(this,query,pos,caseFold)}),CodeMirror.defineExtension("selectMatches",function(query,caseFold){for(var ranges=[],cur=this.getSearchCursor(query,this.getCursor("from"),caseFold);cur.findNext()&&!(CodeMirror.cmpPos(cur.to(),this.getCursor("to"))>0);)ranges.push({anchor:cur.from(),head:cur.to()});ranges.length&&this.setSelections(ranges,0)})})},{"../../lib/codemirror":63}],62:[function(require,module,exports){!function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/edit/matchbrackets")):mod(CodeMirror)}(function(CodeMirror){"use strict";function findPosSubword(doc,start,dir){if(dir<0&&0==start.ch)return doc.clipPos(Pos(start.line-1));var line=doc.getLine(start.line);if(dir>0&&start.ch>=line.length)return doc.clipPos(Pos(start.line+1,0));for(var type,state="start",pos=start.ch,e=dir<0?0:line.length,i=0;pos!=e;pos+=dir,i++){var next=line.charAt(dir<0?pos-1:pos),cat="_"!=next&&CodeMirror.isWordChar(next)?"w":"o";if("w"==cat&&next.toUpperCase()==next&&(cat="W"),"start"==state)"o"!=cat&&(state="in",type=cat);else if("in"==state&&type!=cat){if("w"==type&&"W"==cat&&dir<0&&pos--,"W"==type&&"w"==cat&&dir>0){type="w";continue}break}}return Pos(start.line,pos)}function moveSubword(cm,dir){cm.extendSelectionsBy(function(range){return cm.display.shift||cm.doc.extend||range.empty()?findPosSubword(cm.doc,range.head,dir):dir<0?range.from():range.to()})}function insertLine(cm,above){if(cm.isReadOnly())return CodeMirror.Pass;cm.operation(function(){for(var len=cm.listSelections().length,newSelection=[],last=-1,i=0;i<len;i++){var head=cm.listSelections()[i].head;if(!(head.line<=last)){var at=Pos(head.line+(above?0:1),0);cm.replaceRange("\n",at,null,"+insertLine"),cm.indentLine(at.line,null,!0),newSelection.push({head:at,anchor:at}),last=head.line+1}}cm.setSelections(newSelection)}),cm.execCommand("indentAuto")}function wordAt(cm,pos){for(var start=pos.ch,end=start,line=cm.getLine(pos.line);start&&CodeMirror.isWordChar(line.charAt(start-1));)--start;for(;end<line.length&&CodeMirror.isWordChar(line.charAt(end));)++end;return{from:Pos(pos.line,start),to:Pos(pos.line,end),word:line.slice(start,end)}}function isSelectedRange(ranges,from,to){for(var i=0;i<ranges.length;i++)if(ranges[i].from()==from&&ranges[i].to()==to)return!0;return!1}function selectBetweenBrackets(cm){for(var ranges=cm.listSelections(),newRanges=[],i=0;i<ranges.length;i++){var pos=ranges[i].head,opening=cm.scanForBracket(pos,-1);if(!opening)return!1;for(;;){var closing=cm.scanForBracket(pos,1);if(!closing)return!1;if(closing.ch==mirror.charAt(mirror.indexOf(opening.ch)+1)){newRanges.push({anchor:Pos(opening.pos.line,opening.pos.ch+1),head:closing.pos});break}pos=Pos(closing.pos.line,closing.pos.ch+1)}}return cm.setSelections(newRanges),!0}function sortLines(cm,caseSensitive){if(cm.isReadOnly())return CodeMirror.Pass;for(var selected,ranges=cm.listSelections(),toSort=[],i=0;i<ranges.length;i++){var range=ranges[i];if(!range.empty()){for(var from=range.from().line,to=range.to().line;i<ranges.length-1&&ranges[i+1].from().line==to;)to=ranges[++i].to().line;ranges[i].to().ch||to--,toSort.push(from,to)}}toSort.length?selected=!0:toSort.push(cm.firstLine(),cm.lastLine()),cm.operation(function(){for(var ranges=[],i=0;i<toSort.length;i+=2){var from=toSort[i],to=toSort[i+1],start=Pos(from,0),end=Pos(to),lines=cm.getRange(start,end,!1);caseSensitive?lines.sort():lines.sort(function(a,b){var au=a.toUpperCase(),bu=b.toUpperCase();return au!=bu&&(a=au,b=bu),a<b?-1:a==b?0:1}),cm.replaceRange(lines,start,end),selected&&ranges.push({anchor:start,head:Pos(to+1,0)})}selected&&cm.setSelections(ranges,0)})}function modifyWordOrSelection(cm,mod){cm.operation(function(){for(var ranges=cm.listSelections(),indices=[],replacements=[],i=0;i<ranges.length;i++)(range=ranges[i]).empty()?(indices.push(i),replacements.push("")):replacements.push(mod(cm.getRange(range.from(),range.to())));cm.replaceSelections(replacements,"around","case");for(var at,i=indices.length-1;i>=0;i--){var range=ranges[indices[i]];if(!(at&&CodeMirror.cmpPos(range.head,at)>0)){var word=wordAt(cm,range.head);at=word.from,cm.replaceRange(mod(word.word),word.from,word.to)}}})}function getTarget(cm){var from=cm.getCursor("from"),to=cm.getCursor("to");if(0==CodeMirror.cmpPos(from,to)){var word=wordAt(cm,from);if(!word.word)return;from=word.from,to=word.to}return{from:from,to:to,query:cm.getRange(from,to),word:word}}function findAndGoTo(cm,forward){var target=getTarget(cm);if(target){var query=target.query,cur=cm.getSearchCursor(query,forward?target.to:target.from);(forward?cur.findNext():cur.findPrevious())?cm.setSelection(cur.from(),cur.to()):(cur=cm.getSearchCursor(query,forward?Pos(cm.firstLine(),0):cm.clipPos(Pos(cm.lastLine()))),(forward?cur.findNext():cur.findPrevious())?cm.setSelection(cur.from(),cur.to()):target.word&&cm.setSelection(target.from,target.to))}}var map=CodeMirror.keyMap.sublime={fallthrough:"default"},cmds=CodeMirror.commands,Pos=CodeMirror.Pos,mac=CodeMirror.keyMap.default==CodeMirror.keyMap.macDefault,ctrl=mac?"Cmd-":"Ctrl-",goSubwordCombo=mac?"Ctrl-":"Alt-";cmds[map[goSubwordCombo+"Left"]="goSubwordLeft"]=function(cm){moveSubword(cm,-1)},cmds[map[goSubwordCombo+"Right"]="goSubwordRight"]=function(cm){moveSubword(cm,1)},mac&&(map["Cmd-Left"]="goLineStartSmart");var scrollLineCombo=mac?"Ctrl-Alt-":"Ctrl-";cmds[map[scrollLineCombo+"Up"]="scrollLineUp"]=function(cm){var info=cm.getScrollInfo();if(!cm.somethingSelected()){var visibleBottomLine=cm.lineAtHeight(info.top+info.clientHeight,"local");cm.getCursor().line>=visibleBottomLine&&cm.execCommand("goLineUp")}cm.scrollTo(null,info.top-cm.defaultTextHeight())},cmds[map[scrollLineCombo+"Down"]="scrollLineDown"]=function(cm){var info=cm.getScrollInfo();if(!cm.somethingSelected()){var visibleTopLine=cm.lineAtHeight(info.top,"local")+1;cm.getCursor().line<=visibleTopLine&&cm.execCommand("goLineDown")}cm.scrollTo(null,info.top+cm.defaultTextHeight())},cmds[map["Shift-"+ctrl+"L"]="splitSelectionByLine"]=function(cm){for(var ranges=cm.listSelections(),lineRanges=[],i=0;i<ranges.length;i++)for(var from=ranges[i].from(),to=ranges[i].to(),line=from.line;line<=to.line;++line)to.line>from.line&&line==to.line&&0==to.ch||lineRanges.push({anchor:line==from.line?from:Pos(line,0),head:line==to.line?to:Pos(line)});cm.setSelections(lineRanges,0)},map["Shift-Tab"]="indentLess",cmds[map.Esc="singleSelectionTop"]=function(cm){var range=cm.listSelections()[0];cm.setSelection(range.anchor,range.head,{scroll:!1})},cmds[map[ctrl+"L"]="selectLine"]=function(cm){for(var ranges=cm.listSelections(),extended=[],i=0;i<ranges.length;i++){var range=ranges[i];extended.push({anchor:Pos(range.from().line,0),head:Pos(range.to().line+1,0)})}cm.setSelections(extended)},map["Shift-Ctrl-K"]="deleteLine",cmds[map[ctrl+"Enter"]="insertLineAfter"]=function(cm){return insertLine(cm,!1)},cmds[map["Shift-"+ctrl+"Enter"]="insertLineBefore"]=function(cm){return insertLine(cm,!0)},cmds[map[ctrl+"D"]="selectNextOccurrence"]=function(cm){var from=cm.getCursor("from"),to=cm.getCursor("to"),fullWord=cm.state.sublimeFindFullWord==cm.doc.sel;if(0==CodeMirror.cmpPos(from,to)){var word=wordAt(cm,from);if(!word.word)return;cm.setSelection(word.from,word.to),fullWord=!0}else{var text=cm.getRange(from,to),query=fullWord?new RegExp("\\b"+text+"\\b"):text,cur=cm.getSearchCursor(query,to),found=cur.findNext();if(found||(found=(cur=cm.getSearchCursor(query,Pos(cm.firstLine(),0))).findNext()),!found||isSelectedRange(cm.listSelections(),cur.from(),cur.to()))return CodeMirror.Pass;cm.addSelection(cur.from(),cur.to())}fullWord&&(cm.state.sublimeFindFullWord=cm.doc.sel)};var mirror="(){}[]";cmds[map["Shift-"+ctrl+"Space"]="selectScope"]=function(cm){selectBetweenBrackets(cm)||cm.execCommand("selectAll")},cmds[map["Shift-"+ctrl+"M"]="selectBetweenBrackets"]=function(cm){if(!selectBetweenBrackets(cm))return CodeMirror.Pass},cmds[map[ctrl+"M"]="goToBracket"]=function(cm){cm.extendSelectionsBy(function(range){var next=cm.scanForBracket(range.head,1);if(next&&0!=CodeMirror.cmpPos(next.pos,range.head))return next.pos;var prev=cm.scanForBracket(range.head,-1);return prev&&Pos(prev.pos.line,prev.pos.ch+1)||range.head})};var swapLineCombo=mac?"Cmd-Ctrl-":"Shift-Ctrl-";cmds[map[swapLineCombo+"Up"]="swapLineUp"]=function(cm){if(cm.isReadOnly())return CodeMirror.Pass;for(var ranges=cm.listSelections(),linesToMove=[],at=cm.firstLine()-1,newSels=[],i=0;i<ranges.length;i++){var range=ranges[i],from=range.from().line-1,to=range.to().line;newSels.push({anchor:Pos(range.anchor.line-1,range.anchor.ch),head:Pos(range.head.line-1,range.head.ch)}),0!=range.to().ch||range.empty()||--to,from>at?linesToMove.push(from,to):linesToMove.length&&(linesToMove[linesToMove.length-1]=to),at=to}cm.operation(function(){for(var i=0;i<linesToMove.length;i+=2){var from=linesToMove[i],to=linesToMove[i+1],line=cm.getLine(from);cm.replaceRange("",Pos(from,0),Pos(from+1,0),"+swapLine"),to>cm.lastLine()?cm.replaceRange("\n"+line,Pos(cm.lastLine()),null,"+swapLine"):cm.replaceRange(line+"\n",Pos(to,0),null,"+swapLine")}cm.setSelections(newSels),cm.scrollIntoView()})},cmds[map[swapLineCombo+"Down"]="swapLineDown"]=function(cm){if(cm.isReadOnly())return CodeMirror.Pass;for(var ranges=cm.listSelections(),linesToMove=[],at=cm.lastLine()+1,i=ranges.length-1;i>=0;i--){var range=ranges[i],from=range.to().line+1,to=range.from().line;0!=range.to().ch||range.empty()||from--,from<at?linesToMove.push(from,to):linesToMove.length&&(linesToMove[linesToMove.length-1]=to),at=to}cm.operation(function(){for(var i=linesToMove.length-2;i>=0;i-=2){var from=linesToMove[i],to=linesToMove[i+1],line=cm.getLine(from);from==cm.lastLine()?cm.replaceRange("",Pos(from-1),Pos(from),"+swapLine"):cm.replaceRange("",Pos(from,0),Pos(from+1,0),"+swapLine"),cm.replaceRange(line+"\n",Pos(to,0),null,"+swapLine")}cm.scrollIntoView()})},cmds[map[ctrl+"/"]="toggleCommentIndented"]=function(cm){cm.toggleComment({indent:!0})},cmds[map[ctrl+"J"]="joinLines"]=function(cm){for(var ranges=cm.listSelections(),joined=[],i=0;i<ranges.length;i++){for(var range=ranges[i],from=range.from(),start=from.line,end=range.to().line;i<ranges.length-1&&ranges[i+1].from().line==end;)end=ranges[++i].to().line;joined.push({start:start,end:end,anchor:!range.empty()&&from})}cm.operation(function(){for(var offset=0,ranges=[],i=0;i<joined.length;i++){for(var head,obj=joined[i],anchor=obj.anchor&&Pos(obj.anchor.line-offset,obj.anchor.ch),line=obj.start;line<=obj.end;line++){var actual=line-offset;line==obj.end&&(head=Pos(actual,cm.getLine(actual).length+1)),actual<cm.lastLine()&&(cm.replaceRange(" ",Pos(actual),Pos(actual+1,/^\s*/.exec(cm.getLine(actual+1))[0].length)),++offset)}ranges.push({anchor:anchor||head,head:head})}cm.setSelections(ranges,0)})},cmds[map["Shift-"+ctrl+"D"]="duplicateLine"]=function(cm){cm.operation(function(){for(var rangeCount=cm.listSelections().length,i=0;i<rangeCount;i++){var range=cm.listSelections()[i];range.empty()?cm.replaceRange(cm.getLine(range.head.line)+"\n",Pos(range.head.line,0)):cm.replaceRange(cm.getRange(range.from(),range.to()),range.from())}cm.scrollIntoView()})},mac||(map[ctrl+"T"]="transposeChars"),cmds[map.F9="sortLines"]=function(cm){sortLines(cm,!0)},cmds[map[ctrl+"F9"]="sortLinesInsensitive"]=function(cm){sortLines(cm,!1)},cmds[map.F2="nextBookmark"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(;marks.length;){var current=marks.shift(),found=current.find();if(found)return marks.push(current),cm.setSelection(found.from,found.to)}},cmds[map["Shift-F2"]="prevBookmark"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(;marks.length;){marks.unshift(marks.pop());var found=marks[marks.length-1].find();if(found)return cm.setSelection(found.from,found.to);marks.pop()}},cmds[map[ctrl+"F2"]="toggleBookmark"]=function(cm){for(var ranges=cm.listSelections(),marks=cm.state.sublimeBookmarks||(cm.state.sublimeBookmarks=[]),i=0;i<ranges.length;i++){for(var from=ranges[i].from(),to=ranges[i].to(),found=cm.findMarks(from,to),j=0;j<found.length;j++)if(found[j].sublimeBookmark){found[j].clear();for(var k=0;k<marks.length;k++)marks[k]==found[j]&&marks.splice(k--,1);break}j==found.length&&marks.push(cm.markText(from,to,{sublimeBookmark:!0,clearWhenEmpty:!1}))}},cmds[map["Shift-"+ctrl+"F2"]="clearBookmarks"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(var i=0;i<marks.length;i++)marks[i].clear();marks.length=0},cmds[map["Alt-F2"]="selectBookmarks"]=function(cm){var marks=cm.state.sublimeBookmarks,ranges=[];if(marks)for(var i=0;i<marks.length;i++){var found=marks[i].find();found?ranges.push({anchor:found.from,head:found.to}):marks.splice(i--,0)}ranges.length&&cm.setSelections(ranges,0)},map["Alt-Q"]="wrapLines";var cK=ctrl+"K ";map[cK+ctrl+"Backspace"]="delLineLeft",cmds[map.Backspace="smartBackspace"]=function(cm){if(cm.somethingSelected())return CodeMirror.Pass;cm.operation(function(){for(var cursors=cm.listSelections(),indentUnit=cm.getOption("indentUnit"),i=cursors.length-1;i>=0;i--){var cursor=cursors[i].head,toStartOfLine=cm.getRange({line:cursor.line,ch:0},cursor),column=CodeMirror.countColumn(toStartOfLine,null,cm.getOption("tabSize")),deletePos=cm.findPosH(cursor,-1,"char",!1);if(toStartOfLine&&!/\S/.test(toStartOfLine)&&column%indentUnit==0){var prevIndent=new Pos(cursor.line,CodeMirror.findColumn(toStartOfLine,column-indentUnit,indentUnit));prevIndent.ch!=cursor.ch&&(deletePos=prevIndent)}cm.replaceRange("",deletePos,cursor,"+delete")}})},cmds[map[cK+ctrl+"K"]="delLineRight"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=ranges.length-1;i>=0;i--)cm.replaceRange("",ranges[i].anchor,Pos(ranges[i].to().line),"+delete");cm.scrollIntoView()})},cmds[map[cK+ctrl+"U"]="upcaseAtCursor"]=function(cm){modifyWordOrSelection(cm,function(str){return str.toUpperCase()})},cmds[map[cK+ctrl+"L"]="downcaseAtCursor"]=function(cm){modifyWordOrSelection(cm,function(str){return str.toLowerCase()})},cmds[map[cK+ctrl+"Space"]="setSublimeMark"]=function(cm){cm.state.sublimeMark&&cm.state.sublimeMark.clear(),cm.state.sublimeMark=cm.setBookmark(cm.getCursor())},cmds[map[cK+ctrl+"A"]="selectToSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();found&&cm.setSelection(cm.getCursor(),found)},cmds[map[cK+ctrl+"W"]="deleteToSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();if(found){var from=cm.getCursor(),to=found;if(CodeMirror.cmpPos(from,to)>0){var tmp=to;to=from,from=tmp}cm.state.sublimeKilled=cm.getRange(from,to),cm.replaceRange("",from,to)}},cmds[map[cK+ctrl+"X"]="swapWithSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();found&&(cm.state.sublimeMark.clear(),cm.state.sublimeMark=cm.setBookmark(cm.getCursor()),cm.setCursor(found))},cmds[map[cK+ctrl+"Y"]="sublimeYank"]=function(cm){null!=cm.state.sublimeKilled&&cm.replaceSelection(cm.state.sublimeKilled,null,"paste")},map[cK+ctrl+"G"]="clearBookmarks",cmds[map[cK+ctrl+"C"]="showInCenter"]=function(cm){var pos=cm.cursorCoords(null,"local");cm.scrollTo(null,(pos.top+pos.bottom)/2-cm.getScrollInfo().clientHeight/2)};var selectLinesCombo=mac?"Ctrl-Shift-":"Ctrl-Alt-";cmds[map[selectLinesCombo+"Up"]="selectLinesUpward"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++){var range=ranges[i];range.head.line>cm.firstLine()&&cm.addSelection(Pos(range.head.line-1,range.head.ch))}})},cmds[map[selectLinesCombo+"Down"]="selectLinesDownward"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++){var range=ranges[i];range.head.line<cm.lastLine()&&cm.addSelection(Pos(range.head.line+1,range.head.ch))}})},cmds[map[ctrl+"F3"]="findUnder"]=function(cm){findAndGoTo(cm,!0)},cmds[map["Shift-"+ctrl+"F3"]="findUnderPrevious"]=function(cm){findAndGoTo(cm,!1)},cmds[map["Alt-F3"]="findAllUnder"]=function(cm){var target=getTarget(cm);if(target){for(var cur=cm.getSearchCursor(target.query),matches=[],primaryIndex=-1;cur.findNext();)matches.push({anchor:cur.from(),head:cur.to()}),cur.from().line<=target.from.line&&cur.from().ch<=target.from.ch&&primaryIndex++;cm.setSelections(matches,primaryIndex)}},map["Shift-"+ctrl+"["]="fold",map["Shift-"+ctrl+"]"]="unfold",map[cK+ctrl+"0"]=map[cK+ctrl+"J"]="unfoldAll",map[ctrl+"I"]="findIncremental",map["Shift-"+ctrl+"I"]="findIncrementalReverse",map[ctrl+"H"]="replace",map.F3="findNext",map["Shift-F3"]="findPrev",CodeMirror.normalizeKeyMap(map)})},{"../addon/edit/matchbrackets":54,"../addon/search/searchcursor":61,"../lib/codemirror":63}],63:[function(require,module,exports){!function(global,factory){"object"==typeof exports&&void 0!==module?module.exports=factory():global.CodeMirror=factory()}(this,function(){"use strict";function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}function removeChildren(e){for(var count=e.childNodes.length;count>0;--count)e.removeChild(e.firstChild);return e}function removeChildrenAndAdd(parent,e){return removeChildren(parent).appendChild(e)}function elt(tag,content,className,style){var e=document.createElement(tag);if(className&&(e.className=className),style&&(e.style.cssText=style),"string"==typeof content)e.appendChild(document.createTextNode(content));else if(content)for(var i=0;i<content.length;++i)e.appendChild(content[i]);return e}function eltP(tag,content,className,style){var e=elt(tag,content,className,style);return e.setAttribute("role","presentation"),e}function contains(parent,child){if(3==child.nodeType&&(child=child.parentNode),parent.contains)return parent.contains(child);do{if(11==child.nodeType&&(child=child.host),child==parent)return!0}while(child=child.parentNode)}function activeElt(){var activeElement;try{activeElement=document.activeElement}catch(e){activeElement=document.body||null}for(;activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement;)activeElement=activeElement.shadowRoot.activeElement;return activeElement}function addClass(node,cls){var current=node.className;classTest(cls).test(current)||(node.className+=(current?" ":"")+cls)}function joinClasses(a,b){for(var as=a.split(" "),i=0;i<as.length;i++)as[i]&&!classTest(as[i]).test(b)&&(b+=" "+as[i]);return b}function bind(f){var args=Array.prototype.slice.call(arguments,1);return function(){return f.apply(null,args)}}function copyObj(obj,target,overwrite){target||(target={});for(var prop in obj)!obj.hasOwnProperty(prop)||!1===overwrite&&target.hasOwnProperty(prop)||(target[prop]=obj[prop]);return target}function countColumn(string,end,tabSize,startIndex,startValue){null==end&&-1==(end=string.search(/[^\s\u00a0]/))&&(end=string.length);for(var i=startIndex||0,n=startValue||0;;){var nextTab=string.indexOf("\t",i);if(nextTab<0||nextTab>=end)return n+(end-i);n+=nextTab-i,n+=tabSize-n%tabSize,i=nextTab+1}}function indexOf(array,elt){for(var i=0;i<array.length;++i)if(array[i]==elt)return i;return-1}function findColumn(string,goal,tabSize){for(var pos=0,col=0;;){var nextTab=string.indexOf("\t",pos);-1==nextTab&&(nextTab=string.length);var skipped=nextTab-pos;if(nextTab==string.length||col+skipped>=goal)return pos+Math.min(skipped,goal-col);if(col+=nextTab-pos,col+=tabSize-col%tabSize,pos=nextTab+1,col>=goal)return pos}}function spaceStr(n){for(;spaceStrs.length<=n;)spaceStrs.push(lst(spaceStrs)+" ");return spaceStrs[n]}function lst(arr){return arr[arr.length-1]}function map(array,f){for(var out=[],i=0;i<array.length;i++)out[i]=f(array[i],i);return out}function insertSorted(array,value,score){for(var pos=0,priority=score(value);pos<array.length&&score(array[pos])<=priority;)pos++;array.splice(pos,0,value)}function nothing(){}function createObj(base,props){var inst;return Object.create?inst=Object.create(base):(nothing.prototype=base,inst=new nothing),props&©Obj(props,inst),inst}function isWordCharBasic(ch){return/\w/.test(ch)||ch>""&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch))}function isWordChar(ch,helper){return helper?!!(helper.source.indexOf("\\w")>-1&&isWordCharBasic(ch))||helper.test(ch):isWordCharBasic(ch)}function isEmpty(obj){for(var n in obj)if(obj.hasOwnProperty(n)&&obj[n])return!1;return!0}function isExtendingChar(ch){return ch.charCodeAt(0)>=768&&extendingChars.test(ch)}function skipExtendingChars(str,pos,dir){for(;(dir<0?pos>0:pos<str.length)&&isExtendingChar(str.charAt(pos));)pos+=dir;return pos}function findFirst(pred,from,to){for(;;){if(Math.abs(from-to)<=1)return pred(from)?from:to;var mid=Math.floor((from+to)/2);pred(mid)?to=mid:from=mid}}function Display(place,doc,input){var d=this;this.input=input,d.scrollbarFiller=elt("div",null,"CodeMirror-scrollbar-filler"),d.scrollbarFiller.setAttribute("cm-not-content","true"),d.gutterFiller=elt("div",null,"CodeMirror-gutter-filler"),d.gutterFiller.setAttribute("cm-not-content","true"),d.lineDiv=eltP("div",null,"CodeMirror-code"),d.selectionDiv=elt("div",null,null,"position: relative; z-index: 1"),d.cursorDiv=elt("div",null,"CodeMirror-cursors"),d.measure=elt("div",null,"CodeMirror-measure"),d.lineMeasure=elt("div",null,"CodeMirror-measure"),d.lineSpace=eltP("div",[d.measure,d.lineMeasure,d.selectionDiv,d.cursorDiv,d.lineDiv],null,"position: relative; outline: none");var lines=eltP("div",[d.lineSpace],"CodeMirror-lines");d.mover=elt("div",[lines],null,"position: relative"),d.sizer=elt("div",[d.mover],"CodeMirror-sizer"),d.sizerWidth=null,d.heightForcer=elt("div",null,null,"position: absolute; height: "+scrollerGap+"px; width: 1px;"),d.gutters=elt("div",null,"CodeMirror-gutters"),d.lineGutter=null,d.scroller=elt("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll"),d.scroller.setAttribute("tabIndex","-1"),d.wrapper=elt("div",[d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror"),ie&&ie_version<8&&(d.gutters.style.zIndex=-1,d.scroller.style.paddingRight=0),webkit||gecko&&mobile||(d.scroller.draggable=!0),place&&(place.appendChild?place.appendChild(d.wrapper):place(d.wrapper)),d.viewFrom=d.viewTo=doc.first,d.reportedViewFrom=d.reportedViewTo=doc.first,d.view=[],d.renderedView=null,d.externalMeasured=null,d.viewOffset=0,d.lastWrapHeight=d.lastWrapWidth=0,d.updateLineNumbers=null,d.nativeBarWidth=d.barHeight=d.barWidth=0,d.scrollbarsClipped=!1,d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null,d.alignWidgets=!1,d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null,d.maxLine=null,d.maxLineLength=0,d.maxLineChanged=!1,d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null,d.shift=!1,d.selForContextMenu=null,d.activeTouch=null,input.init(d)}function getLine(doc,n){if((n-=doc.first)<0||n>=doc.size)throw new Error("There is no line "+(n+doc.first)+" in the document.");for(var chunk=doc;!chunk.lines;)for(var i=0;;++i){var child=chunk.children[i],sz=child.chunkSize();if(n<sz){chunk=child;break}n-=sz}return chunk.lines[n]}function getBetween(doc,start,end){var out=[],n=start.line;return doc.iter(start.line,end.line+1,function(line){var text=line.text;n==end.line&&(text=text.slice(0,end.ch)),n==start.line&&(text=text.slice(start.ch)),out.push(text),++n}),out}function getLines(doc,from,to){var out=[];return doc.iter(from,to,function(line){out.push(line.text)}),out}function updateLineHeight(line,height){var diff=height-line.height;if(diff)for(var n=line;n;n=n.parent)n.height+=diff}function lineNo(line){if(null==line.parent)return null;for(var cur=line.parent,no=indexOf(cur.lines,line),chunk=cur.parent;chunk;cur=chunk,chunk=chunk.parent)for(var i=0;chunk.children[i]!=cur;++i)no+=chunk.children[i].chunkSize();return no+cur.first}function lineAtHeight(chunk,h){var n=chunk.first;outer:do{for(var i$1=0;i$1<chunk.children.length;++i$1){var child=chunk.children[i$1],ch=child.height;if(h<ch){chunk=child;continue outer}h-=ch,n+=child.chunkSize()}return n}while(!chunk.lines);for(var i=0;i<chunk.lines.length;++i){var lh=chunk.lines[i].height;if(h<lh)break;h-=lh}return n+i}function isLine(doc,l){return l>=doc.first&&l<doc.first+doc.size}function lineNumberFor(options,i){return String(options.lineNumberFormatter(i+options.firstLineNumber))}function Pos(line,ch,sticky){if(void 0===sticky&&(sticky=null),!(this instanceof Pos))return new Pos(line,ch,sticky);this.line=line,this.ch=ch,this.sticky=sticky}function cmp(a,b){return a.line-b.line||a.ch-b.ch}function equalCursorPos(a,b){return a.sticky==b.sticky&&0==cmp(a,b)}function copyPos(x){return Pos(x.line,x.ch)}function maxPos(a,b){return cmp(a,b)<0?b:a}function minPos(a,b){return cmp(a,b)<0?a:b}function clipLine(doc,n){return Math.max(doc.first,Math.min(n,doc.first+doc.size-1))}function clipPos(doc,pos){if(pos.line<doc.first)return Pos(doc.first,0);var last=doc.first+doc.size-1;return pos.line>last?Pos(last,getLine(doc,last).text.length):clipToLen(pos,getLine(doc,pos.line).text.length)}function clipToLen(pos,linelen){var ch=pos.ch;return null==ch||ch>linelen?Pos(pos.line,linelen):ch<0?Pos(pos.line,0):pos}function clipPosArray(doc,array){for(var out=[],i=0;i<array.length;i++)out[i]=clipPos(doc,array[i]);return out}function seeReadOnlySpans(){sawReadOnlySpans=!0}function seeCollapsedSpans(){sawCollapsedSpans=!0}function MarkedSpan(marker,from,to){this.marker=marker,this.from=from,this.to=to}function getMarkedSpanFor(spans,marker){if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];if(span.marker==marker)return span}}function removeMarkedSpan(spans,span){for(var r,i=0;i<spans.length;++i)spans[i]!=span&&(r||(r=[])).push(spans[i]);return r}function addMarkedSpan(line,span){line.markedSpans=line.markedSpans?line.markedSpans.concat([span]):[span],span.marker.attachLine(line)}function markedSpansBefore(old,startCh,isInsert){var nw;if(old)for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker;if(null==span.from||(marker.inclusiveLeft?span.from<=startCh:span.from<startCh)||span.from==startCh&&"bookmark"==marker.type&&(!isInsert||!span.marker.insertLeft)){var endsAfter=null==span.to||(marker.inclusiveRight?span.to>=startCh:span.to>startCh);(nw||(nw=[])).push(new MarkedSpan(marker,span.from,endsAfter?null:span.to))}}return nw}function markedSpansAfter(old,endCh,isInsert){var nw;if(old)for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker;if(null==span.to||(marker.inclusiveRight?span.to>=endCh:span.to>endCh)||span.from==endCh&&"bookmark"==marker.type&&(!isInsert||span.marker.insertLeft)){var startsBefore=null==span.from||(marker.inclusiveLeft?span.from<=endCh:span.from<endCh);(nw||(nw=[])).push(new MarkedSpan(marker,startsBefore?null:span.from-endCh,null==span.to?null:span.to-endCh))}}return nw}function stretchSpansOverChange(doc,change){if(change.full)return null;var oldFirst=isLine(doc,change.from.line)&&getLine(doc,change.from.line).markedSpans,oldLast=isLine(doc,change.to.line)&&getLine(doc,change.to.line).markedSpans;if(!oldFirst&&!oldLast)return null;var startCh=change.from.ch,endCh=change.to.ch,isInsert=0==cmp(change.from,change.to),first=markedSpansBefore(oldFirst,startCh,isInsert),last=markedSpansAfter(oldLast,endCh,isInsert),sameLine=1==change.text.length,offset=lst(change.text).length+(sameLine?startCh:0);if(first)for(var i=0;i<first.length;++i){var span=first[i];if(null==span.to){var found=getMarkedSpanFor(last,span.marker);found?sameLine&&(span.to=null==found.to?null:found.to+offset):span.to=startCh}}if(last)for(var i$1=0;i$1<last.length;++i$1){var span$1=last[i$1];null!=span$1.to&&(span$1.to+=offset),null==span$1.from?getMarkedSpanFor(first,span$1.marker)||(span$1.from=offset,sameLine&&(first||(first=[])).push(span$1)):(span$1.from+=offset,sameLine&&(first||(first=[])).push(span$1))}first&&(first=clearEmptySpans(first)),last&&last!=first&&(last=clearEmptySpans(last));var newMarkers=[first];if(!sameLine){var gapMarkers,gap=change.text.length-2;if(gap>0&&first)for(var i$2=0;i$2<first.length;++i$2)null==first[i$2].to&&(gapMarkers||(gapMarkers=[])).push(new MarkedSpan(first[i$2].marker,null,null));for(var i$3=0;i$3<gap;++i$3)newMarkers.push(gapMarkers);newMarkers.push(last)}return newMarkers}function clearEmptySpans(spans){for(var i=0;i<spans.length;++i){var span=spans[i];null!=span.from&&span.from==span.to&&!1!==span.marker.clearWhenEmpty&&spans.splice(i--,1)}return spans.length?spans:null}function removeReadOnlyRanges(doc,from,to){var markers=null;if(doc.iter(from.line,to.line+1,function(line){if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var mark=line.markedSpans[i].marker;!mark.readOnly||markers&&-1!=indexOf(markers,mark)||(markers||(markers=[])).push(mark)}}),!markers)return null;for(var parts=[{from:from,to:to}],i=0;i<markers.length;++i)for(var mk=markers[i],m=mk.find(0),j=0;j<parts.length;++j){var p=parts[j];if(!(cmp(p.to,m.from)<0||cmp(p.from,m.to)>0)){var newParts=[j,1],dfrom=cmp(p.from,m.from),dto=cmp(p.to,m.to);(dfrom<0||!mk.inclusiveLeft&&!dfrom)&&newParts.push({from:p.from,to:m.from}),(dto>0||!mk.inclusiveRight&&!dto)&&newParts.push({from:m.to,to:p.to}),parts.splice.apply(parts,newParts),j+=newParts.length-3}}return parts}function detachMarkedSpans(line){var spans=line.markedSpans;if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.detachLine(line);line.markedSpans=null}}function attachMarkedSpans(line,spans){if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.attachLine(line);line.markedSpans=spans}}function extraLeft(marker){return marker.inclusiveLeft?-1:0}function extraRight(marker){return marker.inclusiveRight?1:0}function compareCollapsedMarkers(a,b){var lenDiff=a.lines.length-b.lines.length;if(0!=lenDiff)return lenDiff;var aPos=a.find(),bPos=b.find(),fromCmp=cmp(aPos.from,bPos.from)||extraLeft(a)-extraLeft(b);if(fromCmp)return-fromCmp;var toCmp=cmp(aPos.to,bPos.to)||extraRight(a)-extraRight(b);return toCmp||b.id-a.id}function collapsedSpanAtSide(line,start){var found,sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp=void 0,i=0;i<sps.length;++i)(sp=sps[i]).marker.collapsed&&null==(start?sp.from:sp.to)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)&&(found=sp.marker);return found}function collapsedSpanAtStart(line){return collapsedSpanAtSide(line,!0)}function collapsedSpanAtEnd(line){return collapsedSpanAtSide(line,!1)}function conflictingCollapsedRange(doc,lineNo$$1,from,to,marker){var line=getLine(doc,lineNo$$1),sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var i=0;i<sps.length;++i){var sp=sps[i];if(sp.marker.collapsed){var found=sp.marker.find(0),fromCmp=cmp(found.from,from)||extraLeft(sp.marker)-extraLeft(marker),toCmp=cmp(found.to,to)||extraRight(sp.marker)-extraRight(marker);if(!(fromCmp>=0&&toCmp<=0||fromCmp<=0&&toCmp>=0)&&(fromCmp<=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.to,from)>=0:cmp(found.to,from)>0)||fromCmp>=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.from,to)<=0:cmp(found.from,to)<0)))return!0}}}function visualLine(line){for(var merged;merged=collapsedSpanAtStart(line);)line=merged.find(-1,!0).line;return line}function visualLineEnd(line){for(var merged;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return line}function visualLineContinued(line){for(var merged,lines;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line,(lines||(lines=[])).push(line);return lines}function visualLineNo(doc,lineN){var line=getLine(doc,lineN),vis=visualLine(line);return line==vis?lineN:lineNo(vis)}function visualLineEndNo(doc,lineN){if(lineN>doc.lastLine())return lineN;var merged,line=getLine(doc,lineN);if(!lineIsHidden(doc,line))return lineN;for(;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return lineNo(line)+1}function lineIsHidden(doc,line){var sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp=void 0,i=0;i<sps.length;++i)if((sp=sps[i]).marker.collapsed){if(null==sp.from)return!0;if(!sp.marker.widgetNode&&0==sp.from&&sp.marker.inclusiveLeft&&lineIsHiddenInner(doc,line,sp))return!0}}function lineIsHiddenInner(doc,line,span){if(null==span.to){var end=span.marker.find(1,!0);return lineIsHiddenInner(doc,end.line,getMarkedSpanFor(end.line.markedSpans,span.marker))}if(span.marker.inclusiveRight&&span.to==line.text.length)return!0;for(var sp=void 0,i=0;i<line.markedSpans.length;++i)if((sp=line.markedSpans[i]).marker.collapsed&&!sp.marker.widgetNode&&sp.from==span.to&&(null==sp.to||sp.to!=span.from)&&(sp.marker.inclusiveLeft||span.marker.inclusiveRight)&&lineIsHiddenInner(doc,line,sp))return!0}function heightAtLine(lineObj){for(var h=0,chunk=(lineObj=visualLine(lineObj)).parent,i=0;i<chunk.lines.length;++i){var line=chunk.lines[i];if(line==lineObj)break;h+=line.height}for(var p=chunk.parent;p;chunk=p,p=chunk.parent)for(var i$1=0;i$1<p.children.length;++i$1){var cur=p.children[i$1];if(cur==chunk)break;h+=cur.height}return h}function lineLength(line){if(0==line.height)return 0;for(var merged,len=line.text.length,cur=line;merged=collapsedSpanAtStart(cur);){var found=merged.find(0,!0);cur=found.from.line,len+=found.from.ch-found.to.ch}for(cur=line;merged=collapsedSpanAtEnd(cur);){var found$1=merged.find(0,!0);len-=cur.text.length-found$1.from.ch,len+=(cur=found$1.to.line).text.length-found$1.to.ch}return len}function findMaxLine(cm){var d=cm.display,doc=cm.doc;d.maxLine=getLine(doc,doc.first),d.maxLineLength=lineLength(d.maxLine),d.maxLineChanged=!0,doc.iter(function(line){var len=lineLength(line);len>d.maxLineLength&&(d.maxLineLength=len,d.maxLine=line)})}function iterateBidiSections(order,from,to,f){if(!order)return f(from,to,"ltr");for(var found=!1,i=0;i<order.length;++i){var part=order[i];(part.from<to&&part.to>from||from==to&&part.to==from)&&(f(Math.max(part.from,from),Math.min(part.to,to),1==part.level?"rtl":"ltr"),found=!0)}found||f(from,to,"ltr")}function getBidiPartAt(order,ch,sticky){var found;bidiOther=null;for(var i=0;i<order.length;++i){var cur=order[i];if(cur.from<ch&&cur.to>ch)return i;cur.to==ch&&(cur.from!=cur.to&&"before"==sticky?found=i:bidiOther=i),cur.from==ch&&(cur.from!=cur.to&&"before"!=sticky?found=i:bidiOther=i)}return null!=found?found:bidiOther}function getOrder(line,direction){var order=line.order;return null==order&&(order=line.order=bidiOrdering(line.text,direction)),order}function moveCharLogically(line,ch,dir){var target=skipExtendingChars(line.text,ch+dir,dir);return target<0||target>line.text.length?null:target}function moveLogically(line,start,dir){var ch=moveCharLogically(line,start.ch,dir);return null==ch?null:new Pos(start.line,ch,dir<0?"after":"before")}function endOfLine(visually,cm,lineObj,lineNo,dir){if(visually){var order=getOrder(lineObj,cm.doc.direction);if(order){var ch,part=dir<0?lst(order):order[0],sticky=dir<0==(1==part.level)?"after":"before";if(part.level>0){var prep=prepareMeasureForLine(cm,lineObj);ch=dir<0?lineObj.text.length-1:0;var targetTop=measureCharPrepared(cm,prep,ch).top;ch=findFirst(function(ch){return measureCharPrepared(cm,prep,ch).top==targetTop},dir<0==(1==part.level)?part.from:part.to-1,ch),"before"==sticky&&(ch=moveCharLogically(lineObj,ch,1))}else ch=dir<0?part.to:part.from;return new Pos(lineNo,ch,sticky)}}return new Pos(lineNo,dir<0?lineObj.text.length:0,dir<0?"before":"after")}function moveVisually(cm,line,start,dir){var bidi=getOrder(line,cm.doc.direction);if(!bidi)return moveLogically(line,start,dir);start.ch>=line.text.length?(start.ch=line.text.length,start.sticky="before"):start.ch<=0&&(start.ch=0,start.sticky="after");var partPos=getBidiPartAt(bidi,start.ch,start.sticky),part=bidi[partPos];if("ltr"==cm.doc.direction&&part.level%2==0&&(dir>0?part.to>start.ch:part.from<start.ch))return moveLogically(line,start,dir);var prep,mv=function(pos,dir){return moveCharLogically(line,pos instanceof Pos?pos.ch:pos,dir)},getWrappedLineExtent=function(ch){return cm.options.lineWrapping?(prep=prep||prepareMeasureForLine(cm,line),wrappedLineExtentChar(cm,line,prep,ch)):{begin:0,end:line.text.length}},wrappedLineExtent=getWrappedLineExtent("before"==start.sticky?mv(start,-1):start.ch);if("rtl"==cm.doc.direction||1==part.level){var moveInStorageOrder=1==part.level==dir<0,ch=mv(start,moveInStorageOrder?1:-1);if(null!=ch&&(moveInStorageOrder?ch<=part.to&&ch<=wrappedLineExtent.end:ch>=part.from&&ch>=wrappedLineExtent.begin)){var sticky=moveInStorageOrder?"before":"after";return new Pos(start.line,ch,sticky)}}var searchInVisualLine=function(partPos,dir,wrappedLineExtent){for(var getRes=function(ch,moveInStorageOrder){return moveInStorageOrder?new Pos(start.line,mv(ch,1),"before"):new Pos(start.line,ch,"after")};partPos>=0&&partPos<bidi.length;partPos+=dir){var part=bidi[partPos],moveInStorageOrder=dir>0==(1!=part.level),ch=moveInStorageOrder?wrappedLineExtent.begin:mv(wrappedLineExtent.end,-1);if(part.from<=ch&&ch<part.to)return getRes(ch,moveInStorageOrder);if(ch=moveInStorageOrder?part.from:mv(part.to,-1),wrappedLineExtent.begin<=ch&&ch<wrappedLineExtent.end)return getRes(ch,moveInStorageOrder)}},res=searchInVisualLine(partPos+dir,dir,wrappedLineExtent);if(res)return res;var nextCh=dir>0?wrappedLineExtent.end:mv(wrappedLineExtent.begin,-1);return null==nextCh||dir>0&&nextCh==line.text.length||!(res=searchInVisualLine(dir>0?0:bidi.length-1,dir,getWrappedLineExtent(nextCh)))?null:res}function getHandlers(emitter,type){return emitter._handlers&&emitter._handlers[type]||noHandlers}function off(emitter,type,f){if(emitter.removeEventListener)emitter.removeEventListener(type,f,!1);else if(emitter.detachEvent)emitter.detachEvent("on"+type,f);else{var map$$1=emitter._handlers,arr=map$$1&&map$$1[type];if(arr){var index=indexOf(arr,f);index>-1&&(map$$1[type]=arr.slice(0,index).concat(arr.slice(index+1)))}}}function signal(emitter,type){var handlers=getHandlers(emitter,type);if(handlers.length)for(var args=Array.prototype.slice.call(arguments,2),i=0;i<handlers.length;++i)handlers[i].apply(null,args)}function signalDOMEvent(cm,e,override){return"string"==typeof e&&(e={type:e,preventDefault:function(){this.defaultPrevented=!0}}),signal(cm,override||e.type,cm,e),e_defaultPrevented(e)||e.codemirrorIgnore}function signalCursorActivity(cm){var arr=cm._handlers&&cm._handlers.cursorActivity;if(arr)for(var set=cm.curOp.cursorActivityHandlers||(cm.curOp.cursorActivityHandlers=[]),i=0;i<arr.length;++i)-1==indexOf(set,arr[i])&&set.push(arr[i])}function hasHandler(emitter,type){return getHandlers(emitter,type).length>0}function eventMixin(ctor){ctor.prototype.on=function(type,f){on(this,type,f)},ctor.prototype.off=function(type,f){off(this,type,f)}}function e_preventDefault(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function e_stopPropagation(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function e_defaultPrevented(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function e_stop(e){e_preventDefault(e),e_stopPropagation(e)}function e_target(e){return e.target||e.srcElement}function e_button(e){var b=e.which;return null==b&&(1&e.button?b=1:2&e.button?b=3:4&e.button&&(b=2)),mac&&e.ctrlKey&&1==b&&(b=3),b}function zeroWidthElement(measure){if(null==zwspSupported){var test=elt("span","");removeChildrenAndAdd(measure,elt("span",[test,document.createTextNode("x")])),0!=measure.firstChild.offsetHeight&&(zwspSupported=test.offsetWidth<=1&&test.offsetHeight>2&&!(ie&&ie_version<8))}var node=zwspSupported?elt("span",""):elt("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return node.setAttribute("cm-text",""),node}function hasBadBidiRects(measure){if(null!=badBidiRects)return badBidiRects;var txt=removeChildrenAndAdd(measure,document.createTextNode("AخA")),r0=range(txt,0,1).getBoundingClientRect(),r1=range(txt,1,2).getBoundingClientRect();return removeChildren(measure),!(!r0||r0.left==r0.right)&&(badBidiRects=r1.right-r0.right<3)}function hasBadZoomedRects(measure){if(null!=badZoomedRects)return badZoomedRects;var node=removeChildrenAndAdd(measure,elt("span","x")),normal=node.getBoundingClientRect(),fromRange=range(node,0,1).getBoundingClientRect();return badZoomedRects=Math.abs(normal.left-fromRange.left)>1}function defineMode(name,mode){arguments.length>2&&(mode.dependencies=Array.prototype.slice.call(arguments,2)),modes[name]=mode}function resolveMode(spec){if("string"==typeof spec&&mimeModes.hasOwnProperty(spec))spec=mimeModes[spec];else if(spec&&"string"==typeof spec.name&&mimeModes.hasOwnProperty(spec.name)){var found=mimeModes[spec.name];"string"==typeof found&&(found={name:found}),(spec=createObj(found,spec)).name=found.name}else{if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+xml$/.test(spec))return resolveMode("application/xml");if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+json$/.test(spec))return resolveMode("application/json")}return"string"==typeof spec?{name:spec}:spec||{name:"null"}}function getMode(options,spec){spec=resolveMode(spec);var mfactory=modes[spec.name];if(!mfactory)return getMode(options,"text/plain");var modeObj=mfactory(options,spec);if(modeExtensions.hasOwnProperty(spec.name)){var exts=modeExtensions[spec.name];for(var prop in exts)exts.hasOwnProperty(prop)&&(modeObj.hasOwnProperty(prop)&&(modeObj["_"+prop]=modeObj[prop]),modeObj[prop]=exts[prop])}if(modeObj.name=spec.name,spec.helperType&&(modeObj.helperType=spec.helperType),spec.modeProps)for(var prop$1 in spec.modeProps)modeObj[prop$1]=spec.modeProps[prop$1];return modeObj}function extendMode(mode,properties){copyObj(properties,modeExtensions.hasOwnProperty(mode)?modeExtensions[mode]:modeExtensions[mode]={})}function copyState(mode,state){if(!0===state)return state;if(mode.copyState)return mode.copyState(state);var nstate={};for(var n in state){var val=state[n];val instanceof Array&&(val=val.concat([])),nstate[n]=val}return nstate}function innerMode(mode,state){for(var info;mode.innerMode&&(info=mode.innerMode(state))&&info.mode!=mode;)state=info.state,mode=info.mode;return info||{mode:mode,state:state}}function startState(mode,a1,a2){return!mode.startState||mode.startState(a1,a2)}function highlightLine(cm,line,context,forceToEnd){var st=[cm.state.modeGen],lineClasses={};runMode(cm,line.text,cm.doc.mode,context,function(end,style){return st.push(end,style)},lineClasses,forceToEnd);for(var state=context.state,o=0;o<cm.state.overlays.length;++o)!function(o){var overlay=cm.state.overlays[o],i=1,at=0;context.state=!0,runMode(cm,line.text,overlay.mode,context,function(end,style){for(var start=i;at<end;){var i_end=st[i];i_end>end&&st.splice(i,1,end,st[i+1],i_end),i+=2,at=Math.min(end,i_end)}if(style)if(overlay.opaque)st.splice(start,i-start,end,"overlay "+style),i=start+2;else for(;start<i;start+=2){var cur=st[start+1];st[start+1]=(cur?cur+" ":"")+"overlay "+style}},lineClasses)}(o);return context.state=state,{styles:st,classes:lineClasses.bgClass||lineClasses.textClass?lineClasses:null}}function getLineStyles(cm,line,updateFrontier){if(!line.styles||line.styles[0]!=cm.state.modeGen){var context=getContextBefore(cm,lineNo(line)),resetState=line.text.length>cm.options.maxHighlightLength&©State(cm.doc.mode,context.state),result=highlightLine(cm,line,context);resetState&&(context.state=resetState),line.stateAfter=context.save(!resetState),line.styles=result.styles,result.classes?line.styleClasses=result.classes:line.styleClasses&&(line.styleClasses=null),updateFrontier===cm.doc.highlightFrontier&&(cm.doc.modeFrontier=Math.max(cm.doc.modeFrontier,++cm.doc.highlightFrontier))}return line.styles}function getContextBefore(cm,n,precise){var doc=cm.doc,display=cm.display;if(!doc.mode.startState)return new Context(doc,!0,n);var start=findStartLine(cm,n,precise),saved=start>doc.first&&getLine(doc,start-1).stateAfter,context=saved?Context.fromSaved(doc,saved,start):new Context(doc,startState(doc.mode),start);return doc.iter(start,n,function(line){processLine(cm,line.text,context);var pos=context.line;line.stateAfter=pos==n-1||pos%5==0||pos>=display.viewFrom&&pos<display.viewTo?context.save():null,context.nextLine()}),precise&&(doc.modeFrontier=context.line),context}function processLine(cm,text,context,startAt){var mode=cm.doc.mode,stream=new StringStream(text,cm.options.tabSize,context);for(stream.start=stream.pos=startAt||0,""==text&&callBlankLine(mode,context.state);!stream.eol();)readToken(mode,stream,context.state),stream.start=stream.pos}function callBlankLine(mode,state){if(mode.blankLine)return mode.blankLine(state);if(mode.innerMode){var inner=innerMode(mode,state);return inner.mode.blankLine?inner.mode.blankLine(inner.state):void 0}}function readToken(mode,stream,state,inner){for(var i=0;i<10;i++){inner&&(inner[0]=innerMode(mode,state).mode);var style=mode.token(stream,state);if(stream.pos>stream.start)return style}throw new Error("Mode "+mode.name+" failed to advance stream.")}function takeToken(cm,pos,precise,asArray){var style,tokens,doc=cm.doc,mode=doc.mode,line=getLine(doc,(pos=clipPos(doc,pos)).line),context=getContextBefore(cm,pos.line,precise),stream=new StringStream(line.text,cm.options.tabSize,context);for(asArray&&(tokens=[]);(asArray||stream.pos<pos.ch)&&!stream.eol();)stream.start=stream.pos,style=readToken(mode,stream,context.state),asArray&&tokens.push(new Token(stream,style,copyState(doc.mode,context.state)));return asArray?tokens:new Token(stream,style,context.state)}function extractLineClasses(type,output){if(type)for(;;){var lineClass=type.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!lineClass)break;type=type.slice(0,lineClass.index)+type.slice(lineClass.index+lineClass[0].length);var prop=lineClass[1]?"bgClass":"textClass";null==output[prop]?output[prop]=lineClass[2]:new RegExp("(?:^|s)"+lineClass[2]+"(?:$|s)").test(output[prop])||(output[prop]+=" "+lineClass[2])}return type}function runMode(cm,text,mode,context,f,lineClasses,forceToEnd){var flattenSpans=mode.flattenSpans;null==flattenSpans&&(flattenSpans=cm.options.flattenSpans);var style,curStart=0,curStyle=null,stream=new StringStream(text,cm.options.tabSize,context),inner=cm.options.addModeClass&&[null];for(""==text&&extractLineClasses(callBlankLine(mode,context.state),lineClasses);!stream.eol();){if(stream.pos>cm.options.maxHighlightLength?(flattenSpans=!1,forceToEnd&&processLine(cm,text,context,stream.pos),stream.pos=text.length,style=null):style=extractLineClasses(readToken(mode,stream,context.state,inner),lineClasses),inner){var mName=inner[0].name;mName&&(style="m-"+(style?mName+" "+style:mName))}if(!flattenSpans||curStyle!=style){for(;curStart<stream.start;)f(curStart=Math.min(stream.start,curStart+5e3),curStyle);curStyle=style}stream.start=stream.pos}for(;curStart<stream.pos;){var pos=Math.min(stream.pos,curStart+5e3);f(pos,curStyle),curStart=pos}}function findStartLine(cm,n,precise){for(var minindent,minline,doc=cm.doc,lim=precise?-1:n-(cm.doc.mode.innerMode?1e3:100),search=n;search>lim;--search){if(search<=doc.first)return doc.first;var line=getLine(doc,search-1),after=line.stateAfter;if(after&&(!precise||search+(after instanceof SavedContext?after.lookAhead:0)<=doc.modeFrontier))return search;var indented=countColumn(line.text,null,cm.options.tabSize);(null==minline||minindent>indented)&&(minline=search-1,minindent=indented)}return minline}function retreatFrontier(doc,n){if(doc.modeFrontier=Math.min(doc.modeFrontier,n),!(doc.highlightFrontier<n-10)){for(var start=doc.first,line=n-1;line>start;line--){var saved=getLine(doc,line).stateAfter;if(saved&&(!(saved instanceof SavedContext)||line+saved.lookAhead<n)){start=line+1;break}}doc.highlightFrontier=Math.min(doc.highlightFrontier,start)}}function updateLine(line,text,markedSpans,estimateHeight){line.text=text,line.stateAfter&&(line.stateAfter=null),line.styles&&(line.styles=null),null!=line.order&&(line.order=null),detachMarkedSpans(line),attachMarkedSpans(line,markedSpans);var estHeight=estimateHeight?estimateHeight(line):1;estHeight!=line.height&&updateLineHeight(line,estHeight)}function cleanUpLine(line){line.parent=null,detachMarkedSpans(line)}function interpretTokenStyle(style,options){if(!style||/^\s*$/.test(style))return null;var cache=options.addModeClass?styleToClassCacheWithMode:styleToClassCache;return cache[style]||(cache[style]=style.replace(/\S+/g,"cm-$&"))}function buildLineContent(cm,lineView){var content=eltP("span",null,null,webkit?"padding-right: .1px":null),builder={pre:eltP("pre",[content],"CodeMirror-line"),content:content,col:0,pos:0,cm:cm,trailingSpace:!1,splitSpaces:(ie||webkit)&&cm.getOption("lineWrapping")};lineView.measure={};for(var i=0;i<=(lineView.rest?lineView.rest.length:0);i++){var line=i?lineView.rest[i-1]:lineView.line,order=void 0;builder.pos=0,builder.addToken=buildToken,hasBadBidiRects(cm.display.measure)&&(order=getOrder(line,cm.doc.direction))&&(builder.addToken=buildTokenBadBidi(builder.addToken,order)),builder.map=[],insertLineContent(line,builder,getLineStyles(cm,line,lineView!=cm.display.externalMeasured&&lineNo(line))),line.styleClasses&&(line.styleClasses.bgClass&&(builder.bgClass=joinClasses(line.styleClasses.bgClass,builder.bgClass||"")),line.styleClasses.textClass&&(builder.textClass=joinClasses(line.styleClasses.textClass,builder.textClass||""))),0==builder.map.length&&builder.map.push(0,0,builder.content.appendChild(zeroWidthElement(cm.display.measure))),0==i?(lineView.measure.map=builder.map,lineView.measure.cache={}):((lineView.measure.maps||(lineView.measure.maps=[])).push(builder.map),(lineView.measure.caches||(lineView.measure.caches=[])).push({}))}if(webkit){var last=builder.content.lastChild;(/\bcm-tab\b/.test(last.className)||last.querySelector&&last.querySelector(".cm-tab"))&&(builder.content.className="cm-tab-wrap-hack")}return signal(cm,"renderLine",cm,lineView.line,builder.pre),builder.pre.className&&(builder.textClass=joinClasses(builder.pre.className,builder.textClass||"")),builder}function defaultSpecialCharPlaceholder(ch){var token=elt("span","•","cm-invalidchar");return token.title="\\u"+ch.charCodeAt(0).toString(16),token.setAttribute("aria-label",token.title),token}function buildToken(builder,text,style,startStyle,endStyle,title,css){if(text){var content,displayText=builder.splitSpaces?splitSpaces(text,builder.trailingSpace):text,special=builder.cm.state.specialChars,mustWrap=!1;if(special.test(text)){content=document.createDocumentFragment();for(var pos=0;;){special.lastIndex=pos;var m=special.exec(text),skipped=m?m.index-pos:text.length-pos;if(skipped){var txt=document.createTextNode(displayText.slice(pos,pos+skipped));ie&&ie_version<9?content.appendChild(elt("span",[txt])):content.appendChild(txt),builder.map.push(builder.pos,builder.pos+skipped,txt),builder.col+=skipped,builder.pos+=skipped}if(!m)break;pos+=skipped+1;var txt$1=void 0;if("\t"==m[0]){var tabSize=builder.cm.options.tabSize,tabWidth=tabSize-builder.col%tabSize;(txt$1=content.appendChild(elt("span",spaceStr(tabWidth),"cm-tab"))).setAttribute("role","presentation"),txt$1.setAttribute("cm-text","\t"),builder.col+=tabWidth}else"\r"==m[0]||"\n"==m[0]?((txt$1=content.appendChild(elt("span","\r"==m[0]?"␍":"","cm-invalidchar"))).setAttribute("cm-text",m[0]),builder.col+=1):((txt$1=builder.cm.options.specialCharPlaceholder(m[0])).setAttribute("cm-text",m[0]),ie&&ie_version<9?content.appendChild(elt("span",[txt$1])):content.appendChild(txt$1),builder.col+=1);builder.map.push(builder.pos,builder.pos+1,txt$1),builder.pos++}}else builder.col+=text.length,content=document.createTextNode(displayText),builder.map.push(builder.pos,builder.pos+text.length,content),ie&&ie_version<9&&(mustWrap=!0),builder.pos+=text.length;if(builder.trailingSpace=32==displayText.charCodeAt(text.length-1),style||startStyle||endStyle||mustWrap||css){var fullStyle=style||"";startStyle&&(fullStyle+=startStyle),endStyle&&(fullStyle+=endStyle);var token=elt("span",[content],fullStyle,css);return title&&(token.title=title),builder.content.appendChild(token)}builder.content.appendChild(content)}}function splitSpaces(text,trailingBefore){if(text.length>1&&!/ /.test(text))return text;for(var spaceBefore=trailingBefore,result="",i=0;i<text.length;i++){var ch=text.charAt(i);" "!=ch||!spaceBefore||i!=text.length-1&&32!=text.charCodeAt(i+1)||(ch=" "),result+=ch,spaceBefore=" "==ch}return result}function buildTokenBadBidi(inner,order){return function(builder,text,style,startStyle,endStyle,title,css){style=style?style+" cm-force-border":"cm-force-border";for(var start=builder.pos,end=start+text.length;;){for(var part=void 0,i=0;i<order.length&&!((part=order[i]).to>start&&part.from<=start);i++);if(part.to>=end)return inner(builder,text,style,startStyle,endStyle,title,css);inner(builder,text.slice(0,part.to-start),style,startStyle,null,title,css),startStyle=null,text=text.slice(part.to-start),start=part.to}}}function buildCollapsedSpan(builder,size,marker,ignoreWidget){var widget=!ignoreWidget&&marker.widgetNode;widget&&builder.map.push(builder.pos,builder.pos+size,widget),!ignoreWidget&&builder.cm.display.input.needsContentAttribute&&(widget||(widget=builder.content.appendChild(document.createElement("span"))),widget.setAttribute("cm-marker",marker.id)),widget&&(builder.cm.display.input.setUneditable(widget),builder.content.appendChild(widget)),builder.pos+=size,builder.trailingSpace=!1}function insertLineContent(line,builder,styles){var spans=line.markedSpans,allText=line.text,at=0;if(spans)for(var style,css,spanStyle,spanEndStyle,spanStartStyle,title,collapsed,len=allText.length,pos=0,i=1,text="",nextChange=0;;){if(nextChange==pos){spanStyle=spanEndStyle=spanStartStyle=title=css="",collapsed=null,nextChange=1/0;for(var foundBookmarks=[],endStyles=void 0,j=0;j<spans.length;++j){var sp=spans[j],m=sp.marker;"bookmark"==m.type&&sp.from==pos&&m.widgetNode?foundBookmarks.push(m):sp.from<=pos&&(null==sp.to||sp.to>pos||m.collapsed&&sp.to==pos&&sp.from==pos)?(null!=sp.to&&sp.to!=pos&&nextChange>sp.to&&(nextChange=sp.to,spanEndStyle=""),m.className&&(spanStyle+=" "+m.className),m.css&&(css=(css?css+";":"")+m.css),m.startStyle&&sp.from==pos&&(spanStartStyle+=" "+m.startStyle),m.endStyle&&sp.to==nextChange&&(endStyles||(endStyles=[])).push(m.endStyle,sp.to),m.title&&!title&&(title=m.title),m.collapsed&&(!collapsed||compareCollapsedMarkers(collapsed.marker,m)<0)&&(collapsed=sp)):sp.from>pos&&nextChange>sp.from&&(nextChange=sp.from)}if(endStyles)for(var j$1=0;j$1<endStyles.length;j$1+=2)endStyles[j$1+1]==nextChange&&(spanEndStyle+=" "+endStyles[j$1]);if(!collapsed||collapsed.from==pos)for(var j$2=0;j$2<foundBookmarks.length;++j$2)buildCollapsedSpan(builder,0,foundBookmarks[j$2]);if(collapsed&&(collapsed.from||0)==pos){if(buildCollapsedSpan(builder,(null==collapsed.to?len+1:collapsed.to)-pos,collapsed.marker,null==collapsed.from),null==collapsed.to)return;collapsed.to==pos&&(collapsed=!1)}}if(pos>=len)break;for(var upto=Math.min(len,nextChange);;){if(text){var end=pos+text.length;if(!collapsed){var tokenText=end>upto?text.slice(0,upto-pos):text;builder.addToken(builder,tokenText,style?style+spanStyle:spanStyle,spanStartStyle,pos+tokenText.length==nextChange?spanEndStyle:"",title,css)}if(end>=upto){text=text.slice(upto-pos),pos=upto;break}pos=end,spanStartStyle=""}text=allText.slice(at,at=styles[i++]),style=interpretTokenStyle(styles[i++],builder.cm.options)}}else for(var i$1=1;i$1<styles.length;i$1+=2)builder.addToken(builder,allText.slice(at,at=styles[i$1]),interpretTokenStyle(styles[i$1+1],builder.cm.options))}function LineView(doc,line,lineN){this.line=line,this.rest=visualLineContinued(line),this.size=this.rest?lineNo(lst(this.rest))-lineN+1:1,this.node=this.text=null,this.hidden=lineIsHidden(doc,line)}function buildViewArray(cm,from,to){for(var nextPos,array=[],pos=from;pos<to;pos=nextPos){var view=new LineView(cm.doc,getLine(cm.doc,pos),pos);nextPos=pos+view.size,array.push(view)}return array}function pushOperation(op){operationGroup?operationGroup.ops.push(op):op.ownsGroup=operationGroup={ops:[op],delayedCallbacks:[]}}function fireCallbacksForOps(group){var callbacks=group.delayedCallbacks,i=0;do{for(;i<callbacks.length;i++)callbacks[i].call(null);for(var j=0;j<group.ops.length;j++){var op=group.ops[j];if(op.cursorActivityHandlers)for(;op.cursorActivityCalled<op.cursorActivityHandlers.length;)op.cursorActivityHandlers[op.cursorActivityCalled++].call(null,op.cm)}}while(i<callbacks.length)}function finishOperation(op,endCb){var group=op.ownsGroup;if(group)try{fireCallbacksForOps(group)}finally{operationGroup=null,endCb(group)}}function signalLater(emitter,type){var arr=getHandlers(emitter,type);if(arr.length){var list,args=Array.prototype.slice.call(arguments,2);operationGroup?list=operationGroup.delayedCallbacks:orphanDelayedCallbacks?list=orphanDelayedCallbacks:(list=orphanDelayedCallbacks=[],setTimeout(fireOrphanDelayed,0));for(var i=0;i<arr.length;++i)!function(i){list.push(function(){return arr[i].apply(null,args)})}(i)}}function fireOrphanDelayed(){var delayed=orphanDelayedCallbacks;orphanDelayedCallbacks=null;for(var i=0;i<delayed.length;++i)delayed[i]()}function updateLineForChanges(cm,lineView,lineN,dims){for(var j=0;j<lineView.changes.length;j++){var type=lineView.changes[j];"text"==type?updateLineText(cm,lineView):"gutter"==type?updateLineGutter(cm,lineView,lineN,dims):"class"==type?updateLineClasses(cm,lineView):"widget"==type&&updateLineWidgets(cm,lineView,dims)}lineView.changes=null}function ensureLineWrapped(lineView){return lineView.node==lineView.text&&(lineView.node=elt("div",null,null,"position: relative"),lineView.text.parentNode&&lineView.text.parentNode.replaceChild(lineView.node,lineView.text),lineView.node.appendChild(lineView.text),ie&&ie_version<8&&(lineView.node.style.zIndex=2)),lineView.node}function updateLineBackground(cm,lineView){var cls=lineView.bgClass?lineView.bgClass+" "+(lineView.line.bgClass||""):lineView.line.bgClass;if(cls&&(cls+=" CodeMirror-linebackground"),lineView.background)cls?lineView.background.className=cls:(lineView.background.parentNode.removeChild(lineView.background),lineView.background=null);else if(cls){var wrap=ensureLineWrapped(lineView);lineView.background=wrap.insertBefore(elt("div",null,cls),wrap.firstChild),cm.display.input.setUneditable(lineView.background)}}function getLineContent(cm,lineView){var ext=cm.display.externalMeasured;return ext&&ext.line==lineView.line?(cm.display.externalMeasured=null,lineView.measure=ext.measure,ext.built):buildLineContent(cm,lineView)}function updateLineText(cm,lineView){var cls=lineView.text.className,built=getLineContent(cm,lineView);lineView.text==lineView.node&&(lineView.node=built.pre),lineView.text.parentNode.replaceChild(built.pre,lineView.text),lineView.text=built.pre,built.bgClass!=lineView.bgClass||built.textClass!=lineView.textClass?(lineView.bgClass=built.bgClass,lineView.textClass=built.textClass,updateLineClasses(cm,lineView)):cls&&(lineView.text.className=cls)}function updateLineClasses(cm,lineView){updateLineBackground(cm,lineView),lineView.line.wrapClass?ensureLineWrapped(lineView).className=lineView.line.wrapClass:lineView.node!=lineView.text&&(lineView.node.className="");var textClass=lineView.textClass?lineView.textClass+" "+(lineView.line.textClass||""):lineView.line.textClass;lineView.text.className=textClass||""}function updateLineGutter(cm,lineView,lineN,dims){if(lineView.gutter&&(lineView.node.removeChild(lineView.gutter),lineView.gutter=null),lineView.gutterBackground&&(lineView.node.removeChild(lineView.gutterBackground),lineView.gutterBackground=null),lineView.line.gutterClass){var wrap=ensureLineWrapped(lineView);lineView.gutterBackground=elt("div",null,"CodeMirror-gutter-background "+lineView.line.gutterClass,"left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px; width: "+dims.gutterTotalWidth+"px"),cm.display.input.setUneditable(lineView.gutterBackground),wrap.insertBefore(lineView.gutterBackground,lineView.text)}var markers=lineView.line.gutterMarkers;if(cm.options.lineNumbers||markers){var wrap$1=ensureLineWrapped(lineView),gutterWrap=lineView.gutter=elt("div",null,"CodeMirror-gutter-wrapper","left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px");if(cm.display.input.setUneditable(gutterWrap),wrap$1.insertBefore(gutterWrap,lineView.text),lineView.line.gutterClass&&(gutterWrap.className+=" "+lineView.line.gutterClass),!cm.options.lineNumbers||markers&&markers["CodeMirror-linenumbers"]||(lineView.lineNumber=gutterWrap.appendChild(elt("div",lineNumberFor(cm.options,lineN),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+dims.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+cm.display.lineNumInnerWidth+"px"))),markers)for(var k=0;k<cm.options.gutters.length;++k){var id=cm.options.gutters[k],found=markers.hasOwnProperty(id)&&markers[id];found&&gutterWrap.appendChild(elt("div",[found],"CodeMirror-gutter-elt","left: "+dims.gutterLeft[id]+"px; width: "+dims.gutterWidth[id]+"px"))}}}function updateLineWidgets(cm,lineView,dims){lineView.alignable&&(lineView.alignable=null);for(var node=lineView.node.firstChild,next=void 0;node;node=next)next=node.nextSibling,"CodeMirror-linewidget"==node.className&&lineView.node.removeChild(node);insertLineWidgets(cm,lineView,dims)}function buildLineElement(cm,lineView,lineN,dims){var built=getLineContent(cm,lineView);return lineView.text=lineView.node=built.pre,built.bgClass&&(lineView.bgClass=built.bgClass),built.textClass&&(lineView.textClass=built.textClass),updateLineClasses(cm,lineView),updateLineGutter(cm,lineView,lineN,dims),insertLineWidgets(cm,lineView,dims),lineView.node}function insertLineWidgets(cm,lineView,dims){if(insertLineWidgetsFor(cm,lineView.line,lineView,dims,!0),lineView.rest)for(var i=0;i<lineView.rest.length;i++)insertLineWidgetsFor(cm,lineView.rest[i],lineView,dims,!1)}function insertLineWidgetsFor(cm,line,lineView,dims,allowAbove){if(line.widgets)for(var wrap=ensureLineWrapped(lineView),i=0,ws=line.widgets;i<ws.length;++i){var widget=ws[i],node=elt("div",[widget.node],"CodeMirror-linewidget");widget.handleMouseEvents||node.setAttribute("cm-ignore-events","true"),positionLineWidget(widget,node,lineView,dims),cm.display.input.setUneditable(node),allowAbove&&widget.above?wrap.insertBefore(node,lineView.gutter||lineView.text):wrap.appendChild(node),signalLater(widget,"redraw")}}function positionLineWidget(widget,node,lineView,dims){if(widget.noHScroll){(lineView.alignable||(lineView.alignable=[])).push(node);var width=dims.wrapperWidth;node.style.left=dims.fixedPos+"px",widget.coverGutter||(width-=dims.gutterTotalWidth,node.style.paddingLeft=dims.gutterTotalWidth+"px"),node.style.width=width+"px"}widget.coverGutter&&(node.style.zIndex=5,node.style.position="relative",widget.noHScroll||(node.style.marginLeft=-dims.gutterTotalWidth+"px"))}function widgetHeight(widget){if(null!=widget.height)return widget.height;var cm=widget.doc.cm;if(!cm)return 0;if(!contains(document.body,widget.node)){var parentStyle="position: relative;";widget.coverGutter&&(parentStyle+="margin-left: -"+cm.display.gutters.offsetWidth+"px;"),widget.noHScroll&&(parentStyle+="width: "+cm.display.wrapper.clientWidth+"px;"),removeChildrenAndAdd(cm.display.measure,elt("div",[widget.node],null,parentStyle))}return widget.height=widget.node.parentNode.offsetHeight}function eventInWidget(display,e){for(var n=e_target(e);n!=display.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==display.sizer&&n!=display.mover)return!0}function paddingTop(display){return display.lineSpace.offsetTop}function paddingVert(display){return display.mover.offsetHeight-display.lineSpace.offsetHeight}function paddingH(display){if(display.cachedPaddingH)return display.cachedPaddingH;var e=removeChildrenAndAdd(display.measure,elt("pre","x")),style=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle,data={left:parseInt(style.paddingLeft),right:parseInt(style.paddingRight)};return isNaN(data.left)||isNaN(data.right)||(display.cachedPaddingH=data),data}function scrollGap(cm){return scrollerGap-cm.display.nativeBarWidth}function displayWidth(cm){return cm.display.scroller.clientWidth-scrollGap(cm)-cm.display.barWidth}function displayHeight(cm){return cm.display.scroller.clientHeight-scrollGap(cm)-cm.display.barHeight}function ensureLineHeights(cm,lineView,rect){var wrapping=cm.options.lineWrapping,curWidth=wrapping&&displayWidth(cm);if(!lineView.measure.heights||wrapping&&lineView.measure.width!=curWidth){var heights=lineView.measure.heights=[];if(wrapping){lineView.measure.width=curWidth;for(var rects=lineView.text.firstChild.getClientRects(),i=0;i<rects.length-1;i++){var cur=rects[i],next=rects[i+1];Math.abs(cur.bottom-next.bottom)>2&&heights.push((cur.bottom+next.top)/2-rect.top)}}heights.push(rect.bottom-rect.top)}}function mapFromLineView(lineView,line,lineN){if(lineView.line==line)return{map:lineView.measure.map,cache:lineView.measure.cache};for(var i=0;i<lineView.rest.length;i++)if(lineView.rest[i]==line)return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i]};for(var i$1=0;i$1<lineView.rest.length;i$1++)if(lineNo(lineView.rest[i$1])>lineN)return{map:lineView.measure.maps[i$1],cache:lineView.measure.caches[i$1],before:!0}}function updateExternalMeasurement(cm,line){var lineN=lineNo(line=visualLine(line)),view=cm.display.externalMeasured=new LineView(cm.doc,line,lineN);view.lineN=lineN;var built=view.built=buildLineContent(cm,view);return view.text=built.pre,removeChildrenAndAdd(cm.display.lineMeasure,built.pre),view}function measureChar(cm,line,ch,bias){return measureCharPrepared(cm,prepareMeasureForLine(cm,line),ch,bias)}function findViewForLine(cm,lineN){if(lineN>=cm.display.viewFrom&&lineN<cm.display.viewTo)return cm.display.view[findViewIndex(cm,lineN)];var ext=cm.display.externalMeasured;return ext&&lineN>=ext.lineN&&lineN<ext.lineN+ext.size?ext:void 0}function prepareMeasureForLine(cm,line){var lineN=lineNo(line),view=findViewForLine(cm,lineN);view&&!view.text?view=null:view&&view.changes&&(updateLineForChanges(cm,view,lineN,getDimensions(cm)),cm.curOp.forceUpdate=!0),view||(view=updateExternalMeasurement(cm,line));var info=mapFromLineView(view,line,lineN);return{line:line,view:view,rect:null,map:info.map,cache:info.cache,before:info.before,hasHeights:!1}}function measureCharPrepared(cm,prepared,ch,bias,varHeight){prepared.before&&(ch=-1);var found,key=ch+(bias||"");return prepared.cache.hasOwnProperty(key)?found=prepared.cache[key]:(prepared.rect||(prepared.rect=prepared.view.text.getBoundingClientRect()),prepared.hasHeights||(ensureLineHeights(cm,prepared.view,prepared.rect),prepared.hasHeights=!0),(found=measureCharInner(cm,prepared,ch,bias)).bogus||(prepared.cache[key]=found)),{left:found.left,right:found.right,top:varHeight?found.rtop:found.top,bottom:varHeight?found.rbottom:found.bottom}}function nodeAndOffsetInLineMap(map$$1,ch,bias){for(var node,start,end,collapse,mStart,mEnd,i=0;i<map$$1.length;i+=3)if(mStart=map$$1[i],mEnd=map$$1[i+1],ch<mStart?(start=0,end=1,collapse="left"):ch<mEnd?end=(start=ch-mStart)+1:(i==map$$1.length-3||ch==mEnd&&map$$1[i+3]>ch)&&(start=(end=mEnd-mStart)-1,ch>=mEnd&&(collapse="right")),null!=start){if(node=map$$1[i+2],mStart==mEnd&&bias==(node.insertLeft?"left":"right")&&(collapse=bias),"left"==bias&&0==start)for(;i&&map$$1[i-2]==map$$1[i-3]&&map$$1[i-1].insertLeft;)node=map$$1[2+(i-=3)],collapse="left";if("right"==bias&&start==mEnd-mStart)for(;i<map$$1.length-3&&map$$1[i+3]==map$$1[i+4]&&!map$$1[i+5].insertLeft;)node=map$$1[(i+=3)+2],collapse="right";break}return{node:node,start:start,end:end,collapse:collapse,coverStart:mStart,coverEnd:mEnd}}function getUsefulRect(rects,bias){var rect=nullRect;if("left"==bias)for(var i=0;i<rects.length&&(rect=rects[i]).left==rect.right;i++);else for(var i$1=rects.length-1;i$1>=0&&(rect=rects[i$1]).left==rect.right;i$1--);return rect}function measureCharInner(cm,prepared,ch,bias){var rect,place=nodeAndOffsetInLineMap(prepared.map,ch,bias),node=place.node,start=place.start,end=place.end,collapse=place.collapse;if(3==node.nodeType){for(var i$1=0;i$1<4;i$1++){for(;start&&isExtendingChar(prepared.line.text.charAt(place.coverStart+start));)--start;for(;place.coverStart+end<place.coverEnd&&isExtendingChar(prepared.line.text.charAt(place.coverStart+end));)++end;if((rect=ie&&ie_version<9&&0==start&&end==place.coverEnd-place.coverStart?node.parentNode.getBoundingClientRect():getUsefulRect(range(node,start,end).getClientRects(),bias)).left||rect.right||0==start)break;end=start,start-=1,collapse="right"}ie&&ie_version<11&&(rect=maybeUpdateRectForZooming(cm.display.measure,rect))}else{start>0&&(collapse=bias="right");var rects;rect=cm.options.lineWrapping&&(rects=node.getClientRects()).length>1?rects["right"==bias?rects.length-1:0]:node.getBoundingClientRect()}if(ie&&ie_version<9&&!start&&(!rect||!rect.left&&!rect.right)){var rSpan=node.parentNode.getClientRects()[0];rect=rSpan?{left:rSpan.left,right:rSpan.left+charWidth(cm.display),top:rSpan.top,bottom:rSpan.bottom}:nullRect}for(var rtop=rect.top-prepared.rect.top,rbot=rect.bottom-prepared.rect.top,mid=(rtop+rbot)/2,heights=prepared.view.measure.heights,i=0;i<heights.length-1&&!(mid<heights[i]);i++);var top=i?heights[i-1]:0,bot=heights[i],result={left:("right"==collapse?rect.right:rect.left)-prepared.rect.left,right:("left"==collapse?rect.left:rect.right)-prepared.rect.left,top:top,bottom:bot};return rect.left||rect.right||(result.bogus=!0),cm.options.singleCursorHeightPerLine||(result.rtop=rtop,result.rbottom=rbot),result}function maybeUpdateRectForZooming(measure,rect){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!hasBadZoomedRects(measure))return rect;var scaleX=screen.logicalXDPI/screen.deviceXDPI,scaleY=screen.logicalYDPI/screen.deviceYDPI;return{left:rect.left*scaleX,right:rect.right*scaleX,top:rect.top*scaleY,bottom:rect.bottom*scaleY}}function clearLineMeasurementCacheFor(lineView){if(lineView.measure&&(lineView.measure.cache={},lineView.measure.heights=null,lineView.rest))for(var i=0;i<lineView.rest.length;i++)lineView.measure.caches[i]={}}function clearLineMeasurementCache(cm){cm.display.externalMeasure=null,removeChildren(cm.display.lineMeasure);for(var i=0;i<cm.display.view.length;i++)clearLineMeasurementCacheFor(cm.display.view[i])}function clearCaches(cm){clearLineMeasurementCache(cm),cm.display.cachedCharWidth=cm.display.cachedTextHeight=cm.display.cachedPaddingH=null,cm.options.lineWrapping||(cm.display.maxLineChanged=!0),cm.display.lineNumChars=null}function pageScrollX(){return chrome&&android?-(document.body.getBoundingClientRect().left-parseInt(getComputedStyle(document.body).marginLeft)):window.pageXOffset||(document.documentElement||document.body).scrollLeft}function pageScrollY(){return chrome&&android?-(document.body.getBoundingClientRect().top-parseInt(getComputedStyle(document.body).marginTop)):window.pageYOffset||(document.documentElement||document.body).scrollTop}function intoCoordSystem(cm,lineObj,rect,context,includeWidgets){if(!includeWidgets&&lineObj.widgets)for(var i=0;i<lineObj.widgets.length;++i)if(lineObj.widgets[i].above){var size=widgetHeight(lineObj.widgets[i]);rect.top+=size,rect.bottom+=size}if("line"==context)return rect;context||(context="local");var yOff=heightAtLine(lineObj);if("local"==context?yOff+=paddingTop(cm.display):yOff-=cm.display.viewOffset,"page"==context||"window"==context){var lOff=cm.display.lineSpace.getBoundingClientRect();yOff+=lOff.top+("window"==context?0:pageScrollY());var xOff=lOff.left+("window"==context?0:pageScrollX());rect.left+=xOff,rect.right+=xOff}return rect.top+=yOff,rect.bottom+=yOff,rect}function fromCoordSystem(cm,coords,context){if("div"==context)return coords;var left=coords.left,top=coords.top;if("page"==context)left-=pageScrollX(),top-=pageScrollY();else if("local"==context||!context){var localBox=cm.display.sizer.getBoundingClientRect();left+=localBox.left,top+=localBox.top}var lineSpaceBox=cm.display.lineSpace.getBoundingClientRect();return{left:left-lineSpaceBox.left,top:top-lineSpaceBox.top}}function charCoords(cm,pos,context,lineObj,bias){return lineObj||(lineObj=getLine(cm.doc,pos.line)),intoCoordSystem(cm,lineObj,measureChar(cm,lineObj,pos.ch,bias),context)}function cursorCoords(cm,pos,context,lineObj,preparedMeasure,varHeight){function get(ch,right){var m=measureCharPrepared(cm,preparedMeasure,ch,right?"right":"left",varHeight);return right?m.left=m.right:m.right=m.left,intoCoordSystem(cm,lineObj,m,context)}function getBidi(ch,partPos,invert){var right=order[partPos].level%2!=0;return get(invert?ch-1:ch,right!=invert)}lineObj=lineObj||getLine(cm.doc,pos.line),preparedMeasure||(preparedMeasure=prepareMeasureForLine(cm,lineObj));var order=getOrder(lineObj,cm.doc.direction),ch=pos.ch,sticky=pos.sticky;if(ch>=lineObj.text.length?(ch=lineObj.text.length,sticky="before"):ch<=0&&(ch=0,sticky="after"),!order)return get("before"==sticky?ch-1:ch,"before"==sticky);var partPos=getBidiPartAt(order,ch,sticky),other=bidiOther,val=getBidi(ch,partPos,"before"==sticky);return null!=other&&(val.other=getBidi(ch,other,"before"!=sticky)),val}function estimateCoords(cm,pos){var left=0;pos=clipPos(cm.doc,pos),cm.options.lineWrapping||(left=charWidth(cm.display)*pos.ch);var lineObj=getLine(cm.doc,pos.line),top=heightAtLine(lineObj)+paddingTop(cm.display);return{left:left,right:left,top:top,bottom:top+lineObj.height}}function PosWithInfo(line,ch,sticky,outside,xRel){var pos=Pos(line,ch,sticky);return pos.xRel=xRel,outside&&(pos.outside=!0),pos}function coordsChar(cm,x,y){var doc=cm.doc;if((y+=cm.display.viewOffset)<0)return PosWithInfo(doc.first,0,null,!0,-1);var lineN=lineAtHeight(doc,y),last=doc.first+doc.size-1;if(lineN>last)return PosWithInfo(doc.first+doc.size-1,getLine(doc,last).text.length,null,!0,1);x<0&&(x=0);for(var lineObj=getLine(doc,lineN);;){var found=coordsCharInner(cm,lineObj,lineN,x,y),merged=collapsedSpanAtEnd(lineObj),mergedPos=merged&&merged.find(0,!0);if(!merged||!(found.ch>mergedPos.from.ch||found.ch==mergedPos.from.ch&&found.xRel>0))return found;lineN=lineNo(lineObj=mergedPos.to.line)}}function wrappedLineExtent(cm,lineObj,preparedMeasure,y){var measure=function(ch){return intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,ch),"line")},end=lineObj.text.length,begin=findFirst(function(ch){return measure(ch-1).bottom<=y},end,0);return end=findFirst(function(ch){return measure(ch).top>y},begin,end),{begin:begin,end:end}}function wrappedLineExtentChar(cm,lineObj,preparedMeasure,target){return wrappedLineExtent(cm,lineObj,preparedMeasure,intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,target),"line").top)}function coordsCharInner(cm,lineObj,lineNo$$1,x,y){y-=heightAtLine(lineObj);var pos,begin=0,end=lineObj.text.length,preparedMeasure=prepareMeasureForLine(cm,lineObj);if(getOrder(lineObj,cm.doc.direction)){if(cm.options.lineWrapping){var assign;begin=(assign=wrappedLineExtent(cm,lineObj,preparedMeasure,y)).begin,end=assign.end}pos=new Pos(lineNo$$1,Math.floor(begin+(end-begin)/2));var prevDiff,prevPos,beginLeft=cursorCoords(cm,pos,"line",lineObj,preparedMeasure).left,dir=beginLeft<x?1:-1,diff=beginLeft-x,steps=Math.ceil((end-begin)/4);outer:do{prevDiff=diff,prevPos=pos;for(var i=0;i<steps;++i){var prevPos$1=pos;if(null==(pos=moveVisually(cm,lineObj,pos,dir))||pos.ch<begin||end<=("before"==pos.sticky?pos.ch-1:pos.ch)){pos=prevPos$1;break outer}}if(diff=cursorCoords(cm,pos,"line",lineObj,preparedMeasure).left-x,steps>1){var diff_change_per_step=Math.abs(diff-prevDiff)/steps;steps=Math.min(steps,Math.ceil(Math.abs(diff)/diff_change_per_step)),dir=diff<0?1:-1}}while(0!=diff&&(steps>1||dir<0!=diff<0&&Math.abs(diff)<=Math.abs(prevDiff)));if(Math.abs(diff)>Math.abs(prevDiff)){if(diff<0==prevDiff<0)throw new Error("Broke out of infinite loop in coordsCharInner");pos=prevPos}}else{var ch=findFirst(function(ch){var box=intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,ch),"line");return box.top>y?(end=Math.min(ch,end),!0):!(box.bottom<=y)&&(box.left>x||!(box.right<x)&&x-box.left<box.right-x)},begin,end);pos=new Pos(lineNo$$1,ch=skipExtendingChars(lineObj.text,ch,1),ch==end?"before":"after")}var coords=cursorCoords(cm,pos,"line",lineObj,preparedMeasure);return(y<coords.top||coords.bottom<y)&&(pos.outside=!0),pos.xRel=x<coords.left?-1:x>coords.right?1:0,pos}function textHeight(display){if(null!=display.cachedTextHeight)return display.cachedTextHeight;if(null==measureText){measureText=elt("pre");for(var i=0;i<49;++i)measureText.appendChild(document.createTextNode("x")),measureText.appendChild(elt("br"));measureText.appendChild(document.createTextNode("x"))}removeChildrenAndAdd(display.measure,measureText);var height=measureText.offsetHeight/50;return height>3&&(display.cachedTextHeight=height),removeChildren(display.measure),height||1}function charWidth(display){if(null!=display.cachedCharWidth)return display.cachedCharWidth;var anchor=elt("span","xxxxxxxxxx"),pre=elt("pre",[anchor]);removeChildrenAndAdd(display.measure,pre);var rect=anchor.getBoundingClientRect(),width=(rect.right-rect.left)/10;return width>2&&(display.cachedCharWidth=width),width||10}function getDimensions(cm){for(var d=cm.display,left={},width={},gutterLeft=d.gutters.clientLeft,n=d.gutters.firstChild,i=0;n;n=n.nextSibling,++i)left[cm.options.gutters[i]]=n.offsetLeft+n.clientLeft+gutterLeft,width[cm.options.gutters[i]]=n.clientWidth;return{fixedPos:compensateForHScroll(d),gutterTotalWidth:d.gutters.offsetWidth,gutterLeft:left,gutterWidth:width,wrapperWidth:d.wrapper.clientWidth}}function compensateForHScroll(display){return display.scroller.getBoundingClientRect().left-display.sizer.getBoundingClientRect().left}function estimateHeight(cm){var th=textHeight(cm.display),wrapping=cm.options.lineWrapping,perLine=wrapping&&Math.max(5,cm.display.scroller.clientWidth/charWidth(cm.display)-3);return function(line){if(lineIsHidden(cm.doc,line))return 0;var widgetsHeight=0;if(line.widgets)for(var i=0;i<line.widgets.length;i++)line.widgets[i].height&&(widgetsHeight+=line.widgets[i].height);return wrapping?widgetsHeight+(Math.ceil(line.text.length/perLine)||1)*th:widgetsHeight+th}}function estimateLineHeights(cm){var doc=cm.doc,est=estimateHeight(cm);doc.iter(function(line){var estHeight=est(line);estHeight!=line.height&&updateLineHeight(line,estHeight)})}function posFromMouse(cm,e,liberal,forRect){var display=cm.display;if(!liberal&&"true"==e_target(e).getAttribute("cm-not-content"))return null;var x,y,space=display.lineSpace.getBoundingClientRect();try{x=e.clientX-space.left,y=e.clientY-space.top}catch(e){return null}var line,coords=coordsChar(cm,x,y);if(forRect&&1==coords.xRel&&(line=getLine(cm.doc,coords.line).text).length==coords.ch){var colDiff=countColumn(line,line.length,cm.options.tabSize)-line.length;coords=Pos(coords.line,Math.max(0,Math.round((x-paddingH(cm.display).left)/charWidth(cm.display))-colDiff))}return coords}function findViewIndex(cm,n){if(n>=cm.display.viewTo)return null;if((n-=cm.display.viewFrom)<0)return null;for(var view=cm.display.view,i=0;i<view.length;i++)if((n-=view[i].size)<0)return i}function updateSelection(cm){cm.display.input.showSelection(cm.display.input.prepareSelection())}function prepareSelection(cm,primary){for(var doc=cm.doc,result={},curFragment=result.cursors=document.createDocumentFragment(),selFragment=result.selection=document.createDocumentFragment(),i=0;i<doc.sel.ranges.length;i++)if(!1!==primary||i!=doc.sel.primIndex){var range$$1=doc.sel.ranges[i];if(!(range$$1.from().line>=cm.display.viewTo||range$$1.to().line<cm.display.viewFrom)){var collapsed=range$$1.empty();(collapsed||cm.options.showCursorWhenSelecting)&&drawSelectionCursor(cm,range$$1.head,curFragment),collapsed||drawSelectionRange(cm,range$$1,selFragment)}}return result}function drawSelectionCursor(cm,head,output){var pos=cursorCoords(cm,head,"div",null,null,!cm.options.singleCursorHeightPerLine),cursor=output.appendChild(elt("div"," ","CodeMirror-cursor"));if(cursor.style.left=pos.left+"px",cursor.style.top=pos.top+"px",cursor.style.height=Math.max(0,pos.bottom-pos.top)*cm.options.cursorHeight+"px",pos.other){var otherCursor=output.appendChild(elt("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));otherCursor.style.display="",otherCursor.style.left=pos.other.left+"px",otherCursor.style.top=pos.other.top+"px",otherCursor.style.height=.85*(pos.other.bottom-pos.other.top)+"px"}}function drawSelectionRange(cm,range$$1,output){function add(left,top,width,bottom){top<0&&(top=0),top=Math.round(top),bottom=Math.round(bottom),fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(null==width?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px"))}function drawForLine(line,fromArg,toArg){function coords(ch,bias){return charCoords(cm,Pos(line,ch),"div",lineObj,bias)}var start,end,lineObj=getLine(doc,line),lineLen=lineObj.text.length;return iterateBidiSections(getOrder(lineObj,doc.direction),fromArg||0,null==toArg?lineLen:toArg,function(from,to,dir){var rightPos,left,right,leftPos=coords(from,"left");if(from==to)rightPos=leftPos,left=right=leftPos.left;else{if(rightPos=coords(to-1,"right"),"rtl"==dir){var tmp=leftPos;leftPos=rightPos,rightPos=tmp}left=leftPos.left,right=rightPos.right}null==fromArg&&0==from&&(left=leftSide),rightPos.top-leftPos.top>3&&(add(left,leftPos.top,null,leftPos.bottom),left=leftSide,leftPos.bottom<rightPos.top&&add(left,leftPos.bottom,null,rightPos.top)),null==toArg&&to==lineLen&&(right=rightSide),(!start||leftPos.top<start.top||leftPos.top==start.top&&leftPos.left<start.left)&&(start=leftPos),(!end||rightPos.bottom>end.bottom||rightPos.bottom==end.bottom&&rightPos.right>end.right)&&(end=rightPos),left<leftSide+1&&(left=leftSide),add(left,rightPos.top,right-left,rightPos.bottom)}),{start:start,end:end}}var display=cm.display,doc=cm.doc,fragment=document.createDocumentFragment(),padding=paddingH(cm.display),leftSide=padding.left,rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right,sFrom=range$$1.from(),sTo=range$$1.to();if(sFrom.line==sTo.line)drawForLine(sFrom.line,sFrom.ch,sTo.ch);else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line),singleVLine=visualLine(fromLine)==visualLine(toLine),leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end,rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start;singleVLine&&(leftEnd.top<rightStart.top-2?(add(leftEnd.right,leftEnd.top,null,leftEnd.bottom),add(leftSide,rightStart.top,rightStart.left,rightStart.bottom)):add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom)),leftEnd.bottom<rightStart.top&&add(leftSide,leftEnd.bottom,null,rightStart.top)}output.appendChild(fragment)}function restartBlink(cm){if(cm.state.focused){var display=cm.display;clearInterval(display.blinker);var on=!0;display.cursorDiv.style.visibility="",cm.options.cursorBlinkRate>0?display.blinker=setInterval(function(){return display.cursorDiv.style.visibility=(on=!on)?"":"hidden"},cm.options.cursorBlinkRate):cm.options.cursorBlinkRate<0&&(display.cursorDiv.style.visibility="hidden")}}function ensureFocus(cm){cm.state.focused||(cm.display.input.focus(),onFocus(cm))}function delayBlurEvent(cm){cm.state.delayingBlurEvent=!0,setTimeout(function(){cm.state.delayingBlurEvent&&(cm.state.delayingBlurEvent=!1,onBlur(cm))},100)}function onFocus(cm,e){cm.state.delayingBlurEvent&&(cm.state.delayingBlurEvent=!1),"nocursor"!=cm.options.readOnly&&(cm.state.focused||(signal(cm,"focus",cm,e),cm.state.focused=!0,addClass(cm.display.wrapper,"CodeMirror-focused"),cm.curOp||cm.display.selForContextMenu==cm.doc.sel||(cm.display.input.reset(),webkit&&setTimeout(function(){return cm.display.input.reset(!0)},20)),cm.display.input.receivedFocus()),restartBlink(cm))}function onBlur(cm,e){cm.state.delayingBlurEvent||(cm.state.focused&&(signal(cm,"blur",cm,e),cm.state.focused=!1,rmClass(cm.display.wrapper,"CodeMirror-focused")),clearInterval(cm.display.blinker),setTimeout(function(){cm.state.focused||(cm.display.shift=!1)},150))}function updateHeightsInViewport(cm){for(var display=cm.display,prevBottom=display.lineDiv.offsetTop,i=0;i<display.view.length;i++){var cur=display.view[i],height=void 0;if(!cur.hidden){if(ie&&ie_version<8){var bot=cur.node.offsetTop+cur.node.offsetHeight;height=bot-prevBottom,prevBottom=bot}else{var box=cur.node.getBoundingClientRect();height=box.bottom-box.top}var diff=cur.line.height-height;if(height<2&&(height=textHeight(display)),(diff>.001||diff<-.001)&&(updateLineHeight(cur.line,height),updateWidgetHeight(cur.line),cur.rest))for(var j=0;j<cur.rest.length;j++)updateWidgetHeight(cur.rest[j])}}}function updateWidgetHeight(line){if(line.widgets)for(var i=0;i<line.widgets.length;++i)line.widgets[i].height=line.widgets[i].node.parentNode.offsetHeight}function visibleLines(display,doc,viewport){var top=viewport&&null!=viewport.top?Math.max(0,viewport.top):display.scroller.scrollTop;top=Math.floor(top-paddingTop(display));var bottom=viewport&&null!=viewport.bottom?viewport.bottom:top+display.wrapper.clientHeight,from=lineAtHeight(doc,top),to=lineAtHeight(doc,bottom);if(viewport&&viewport.ensure){var ensureFrom=viewport.ensure.from.line,ensureTo=viewport.ensure.to.line;ensureFrom<from?(from=ensureFrom,to=lineAtHeight(doc,heightAtLine(getLine(doc,ensureFrom))+display.wrapper.clientHeight)):Math.min(ensureTo,doc.lastLine())>=to&&(from=lineAtHeight(doc,heightAtLine(getLine(doc,ensureTo))-display.wrapper.clientHeight),to=ensureTo)}return{from:from,to:Math.max(to,from+1)}}function alignHorizontally(cm){var display=cm.display,view=display.view;if(display.alignWidgets||display.gutters.firstChild&&cm.options.fixedGutter){for(var comp=compensateForHScroll(display)-display.scroller.scrollLeft+cm.doc.scrollLeft,gutterW=display.gutters.offsetWidth,left=comp+"px",i=0;i<view.length;i++)if(!view[i].hidden){cm.options.fixedGutter&&(view[i].gutter&&(view[i].gutter.style.left=left),view[i].gutterBackground&&(view[i].gutterBackground.style.left=left));var align=view[i].alignable;if(align)for(var j=0;j<align.length;j++)align[j].style.left=left}cm.options.fixedGutter&&(display.gutters.style.left=comp+gutterW+"px")}}function maybeUpdateLineNumberWidth(cm){if(!cm.options.lineNumbers)return!1;var doc=cm.doc,last=lineNumberFor(cm.options,doc.first+doc.size-1),display=cm.display;if(last.length!=display.lineNumChars){var test=display.measure.appendChild(elt("div",[elt("div",last)],"CodeMirror-linenumber CodeMirror-gutter-elt")),innerW=test.firstChild.offsetWidth,padding=test.offsetWidth-innerW;return display.lineGutter.style.width="",display.lineNumInnerWidth=Math.max(innerW,display.lineGutter.offsetWidth-padding)+1,display.lineNumWidth=display.lineNumInnerWidth+padding,display.lineNumChars=display.lineNumInnerWidth?last.length:-1,display.lineGutter.style.width=display.lineNumWidth+"px",updateGutterSpace(cm),!0}return!1}function maybeScrollWindow(cm,rect){if(!signalDOMEvent(cm,"scrollCursorIntoView")){var display=cm.display,box=display.sizer.getBoundingClientRect(),doScroll=null;if(rect.top+box.top<0?doScroll=!0:rect.bottom+box.top>(window.innerHeight||document.documentElement.clientHeight)&&(doScroll=!1),null!=doScroll&&!phantom){var scrollNode=elt("div","",null,"position: absolute;\n top: "+(rect.top-display.viewOffset-paddingTop(cm.display))+"px;\n height: "+(rect.bottom-rect.top+scrollGap(cm)+display.barHeight)+"px;\n left: "+rect.left+"px; width: "+Math.max(2,rect.right-rect.left)+"px;");cm.display.lineSpace.appendChild(scrollNode),scrollNode.scrollIntoView(doScroll),cm.display.lineSpace.removeChild(scrollNode)}}}function scrollPosIntoView(cm,pos,end,margin){null==margin&&(margin=0);for(var rect,limit=0;limit<5;limit++){var changed=!1,coords=cursorCoords(cm,pos),endCoords=end&&end!=pos?cursorCoords(cm,end):coords,scrollPos=calculateScrollPos(cm,rect={left:Math.min(coords.left,endCoords.left),top:Math.min(coords.top,endCoords.top)-margin,right:Math.max(coords.left,endCoords.left),bottom:Math.max(coords.bottom,endCoords.bottom)+margin}),startTop=cm.doc.scrollTop,startLeft=cm.doc.scrollLeft;if(null!=scrollPos.scrollTop&&(updateScrollTop(cm,scrollPos.scrollTop),Math.abs(cm.doc.scrollTop-startTop)>1&&(changed=!0)),null!=scrollPos.scrollLeft&&(setScrollLeft(cm,scrollPos.scrollLeft),Math.abs(cm.doc.scrollLeft-startLeft)>1&&(changed=!0)),!changed)break}return rect}function scrollIntoView(cm,rect){var scrollPos=calculateScrollPos(cm,rect);null!=scrollPos.scrollTop&&updateScrollTop(cm,scrollPos.scrollTop),null!=scrollPos.scrollLeft&&setScrollLeft(cm,scrollPos.scrollLeft)}function calculateScrollPos(cm,rect){var display=cm.display,snapMargin=textHeight(cm.display);rect.top<0&&(rect.top=0);var screentop=cm.curOp&&null!=cm.curOp.scrollTop?cm.curOp.scrollTop:display.scroller.scrollTop,screen=displayHeight(cm),result={};rect.bottom-rect.top>screen&&(rect.bottom=rect.top+screen);var docBottom=cm.doc.height+paddingVert(display),atTop=rect.top<snapMargin,atBottom=rect.bottom>docBottom-snapMargin;if(rect.top<screentop)result.scrollTop=atTop?0:rect.top;else if(rect.bottom>screentop+screen){var newTop=Math.min(rect.top,(atBottom?docBottom:rect.bottom)-screen);newTop!=screentop&&(result.scrollTop=newTop)}var screenleft=cm.curOp&&null!=cm.curOp.scrollLeft?cm.curOp.scrollLeft:display.scroller.scrollLeft,screenw=displayWidth(cm)-(cm.options.fixedGutter?display.gutters.offsetWidth:0),tooWide=rect.right-rect.left>screenw;return tooWide&&(rect.right=rect.left+screenw),rect.left<10?result.scrollLeft=0:rect.left<screenleft?result.scrollLeft=Math.max(0,rect.left-(tooWide?0:10)):rect.right>screenw+screenleft-3&&(result.scrollLeft=rect.right+(tooWide?0:10)-screenw),result}function addToScrollTop(cm,top){null!=top&&(resolveScrollToPos(cm),cm.curOp.scrollTop=(null==cm.curOp.scrollTop?cm.doc.scrollTop:cm.curOp.scrollTop)+top)}function ensureCursorVisible(cm){resolveScrollToPos(cm);var cur=cm.getCursor(),from=cur,to=cur;cm.options.lineWrapping||(from=cur.ch?Pos(cur.line,cur.ch-1):cur,to=Pos(cur.line,cur.ch+1)),cm.curOp.scrollToPos={from:from,to:to,margin:cm.options.cursorScrollMargin}}function scrollToCoords(cm,x,y){null==x&&null==y||resolveScrollToPos(cm),null!=x&&(cm.curOp.scrollLeft=x),null!=y&&(cm.curOp.scrollTop=y)}function scrollToRange(cm,range$$1){resolveScrollToPos(cm),cm.curOp.scrollToPos=range$$1}function resolveScrollToPos(cm){var range$$1=cm.curOp.scrollToPos;range$$1&&(cm.curOp.scrollToPos=null,scrollToCoordsRange(cm,estimateCoords(cm,range$$1.from),estimateCoords(cm,range$$1.to),range$$1.margin))}function scrollToCoordsRange(cm,from,to,margin){var sPos=calculateScrollPos(cm,{left:Math.min(from.left,to.left),top:Math.min(from.top,to.top)-margin,right:Math.max(from.right,to.right),bottom:Math.max(from.bottom,to.bottom)+margin});scrollToCoords(cm,sPos.scrollLeft,sPos.scrollTop)}function updateScrollTop(cm,val){Math.abs(cm.doc.scrollTop-val)<2||(gecko||updateDisplaySimple(cm,{top:val}),setScrollTop(cm,val,!0),gecko&&updateDisplaySimple(cm),startWorker(cm,100))}function setScrollTop(cm,val,forceScroll){val=Math.min(cm.display.scroller.scrollHeight-cm.display.scroller.clientHeight,val),(cm.display.scroller.scrollTop!=val||forceScroll)&&(cm.doc.scrollTop=val,cm.display.scrollbars.setScrollTop(val),cm.display.scroller.scrollTop!=val&&(cm.display.scroller.scrollTop=val))}function setScrollLeft(cm,val,isScroller,forceScroll){val=Math.min(val,cm.display.scroller.scrollWidth-cm.display.scroller.clientWidth),(isScroller?val==cm.doc.scrollLeft:Math.abs(cm.doc.scrollLeft-val)<2)&&!forceScroll||(cm.doc.scrollLeft=val,alignHorizontally(cm),cm.display.scroller.scrollLeft!=val&&(cm.display.scroller.scrollLeft=val),cm.display.scrollbars.setScrollLeft(val))}function measureForScrollbars(cm){var d=cm.display,gutterW=d.gutters.offsetWidth,docH=Math.round(cm.doc.height+paddingVert(cm.display));return{clientHeight:d.scroller.clientHeight,viewHeight:d.wrapper.clientHeight,scrollWidth:d.scroller.scrollWidth,clientWidth:d.scroller.clientWidth,viewWidth:d.wrapper.clientWidth,barLeft:cm.options.fixedGutter?gutterW:0,docHeight:docH,scrollHeight:docH+scrollGap(cm)+d.barHeight,nativeBarWidth:d.nativeBarWidth,gutterWidth:gutterW}}function updateScrollbars(cm,measure){measure||(measure=measureForScrollbars(cm));var startWidth=cm.display.barWidth,startHeight=cm.display.barHeight;updateScrollbarsInner(cm,measure);for(var i=0;i<4&&startWidth!=cm.display.barWidth||startHeight!=cm.display.barHeight;i++)startWidth!=cm.display.barWidth&&cm.options.lineWrapping&&updateHeightsInViewport(cm),updateScrollbarsInner(cm,measureForScrollbars(cm)),startWidth=cm.display.barWidth,startHeight=cm.display.barHeight}function updateScrollbarsInner(cm,measure){var d=cm.display,sizes=d.scrollbars.update(measure);d.sizer.style.paddingRight=(d.barWidth=sizes.right)+"px",d.sizer.style.paddingBottom=(d.barHeight=sizes.bottom)+"px",d.heightForcer.style.borderBottom=sizes.bottom+"px solid transparent",sizes.right&&sizes.bottom?(d.scrollbarFiller.style.display="block",d.scrollbarFiller.style.height=sizes.bottom+"px",d.scrollbarFiller.style.width=sizes.right+"px"):d.scrollbarFiller.style.display="",sizes.bottom&&cm.options.coverGutterNextToScrollbar&&cm.options.fixedGutter?(d.gutterFiller.style.display="block",d.gutterFiller.style.height=sizes.bottom+"px",d.gutterFiller.style.width=measure.gutterWidth+"px"):d.gutterFiller.style.display=""}function initScrollbars(cm){cm.display.scrollbars&&(cm.display.scrollbars.clear(),cm.display.scrollbars.addClass&&rmClass(cm.display.wrapper,cm.display.scrollbars.addClass)),cm.display.scrollbars=new scrollbarModel[cm.options.scrollbarStyle](function(node){cm.display.wrapper.insertBefore(node,cm.display.scrollbarFiller),on(node,"mousedown",function(){cm.state.focused&&setTimeout(function(){return cm.display.input.focus()},0)}),node.setAttribute("cm-not-content","true")},function(pos,axis){"horizontal"==axis?setScrollLeft(cm,pos):updateScrollTop(cm,pos)},cm),cm.display.scrollbars.addClass&&addClass(cm.display.wrapper,cm.display.scrollbars.addClass)}function startOperation(cm){cm.curOp={cm:cm,viewChanged:!1,startHeight:cm.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++nextOpId},pushOperation(cm.curOp)}function endOperation(cm){finishOperation(cm.curOp,function(group){for(var i=0;i<group.ops.length;i++)group.ops[i].cm.curOp=null;endOperations(group)})}function endOperations(group){for(var ops=group.ops,i=0;i<ops.length;i++)endOperation_R1(ops[i]);for(var i$1=0;i$1<ops.length;i$1++)endOperation_W1(ops[i$1]);for(var i$2=0;i$2<ops.length;i$2++)endOperation_R2(ops[i$2]);for(var i$3=0;i$3<ops.length;i$3++)endOperation_W2(ops[i$3]);for(var i$4=0;i$4<ops.length;i$4++)endOperation_finish(ops[i$4])}function endOperation_R1(op){var cm=op.cm,display=cm.display;maybeClipScrollbars(cm),op.updateMaxLine&&findMaxLine(cm),op.mustUpdate=op.viewChanged||op.forceUpdate||null!=op.scrollTop||op.scrollToPos&&(op.scrollToPos.from.line<display.viewFrom||op.scrollToPos.to.line>=display.viewTo)||display.maxLineChanged&&cm.options.lineWrapping,op.update=op.mustUpdate&&new DisplayUpdate(cm,op.mustUpdate&&{top:op.scrollTop,ensure:op.scrollToPos},op.forceUpdate)}function endOperation_W1(op){op.updatedDisplay=op.mustUpdate&&updateDisplayIfNeeded(op.cm,op.update)}function endOperation_R2(op){var cm=op.cm,display=cm.display;op.updatedDisplay&&updateHeightsInViewport(cm),op.barMeasure=measureForScrollbars(cm),display.maxLineChanged&&!cm.options.lineWrapping&&(op.adjustWidthTo=measureChar(cm,display.maxLine,display.maxLine.text.length).left+3,cm.display.sizerWidth=op.adjustWidthTo,op.barMeasure.scrollWidth=Math.max(display.scroller.clientWidth,display.sizer.offsetLeft+op.adjustWidthTo+scrollGap(cm)+cm.display.barWidth),op.maxScrollLeft=Math.max(0,display.sizer.offsetLeft+op.adjustWidthTo-displayWidth(cm))),(op.updatedDisplay||op.selectionChanged)&&(op.preparedSelection=display.input.prepareSelection(op.focus))}function endOperation_W2(op){var cm=op.cm;null!=op.adjustWidthTo&&(cm.display.sizer.style.minWidth=op.adjustWidthTo+"px",op.maxScrollLeft<cm.doc.scrollLeft&&setScrollLeft(cm,Math.min(cm.display.scroller.scrollLeft,op.maxScrollLeft),!0),cm.display.maxLineChanged=!1);var takeFocus=op.focus&&op.focus==activeElt()&&(!document.hasFocus||document.hasFocus());op.preparedSelection&&cm.display.input.showSelection(op.preparedSelection,takeFocus),(op.updatedDisplay||op.startHeight!=cm.doc.height)&&updateScrollbars(cm,op.barMeasure),op.updatedDisplay&&setDocumentHeight(cm,op.barMeasure),op.selectionChanged&&restartBlink(cm),cm.state.focused&&op.updateInput&&cm.display.input.reset(op.typing),takeFocus&&ensureFocus(op.cm)}function endOperation_finish(op){var cm=op.cm,display=cm.display,doc=cm.doc;op.updatedDisplay&&postUpdateDisplay(cm,op.update),null==display.wheelStartX||null==op.scrollTop&&null==op.scrollLeft&&!op.scrollToPos||(display.wheelStartX=display.wheelStartY=null),null!=op.scrollTop&&setScrollTop(cm,op.scrollTop,op.forceScroll),null!=op.scrollLeft&&setScrollLeft(cm,op.scrollLeft,!0,!0),op.scrollToPos&&maybeScrollWindow(cm,scrollPosIntoView(cm,clipPos(doc,op.scrollToPos.from),clipPos(doc,op.scrollToPos.to),op.scrollToPos.margin));var hidden=op.maybeHiddenMarkers,unhidden=op.maybeUnhiddenMarkers;if(hidden)for(var i=0;i<hidden.length;++i)hidden[i].lines.length||signal(hidden[i],"hide");if(unhidden)for(var i$1=0;i$1<unhidden.length;++i$1)unhidden[i$1].lines.length&&signal(unhidden[i$1],"unhide");display.wrapper.offsetHeight&&(doc.scrollTop=cm.display.scroller.scrollTop),op.changeObjs&&signal(cm,"changes",cm,op.changeObjs),op.update&&op.update.finish()}function runInOp(cm,f){if(cm.curOp)return f();startOperation(cm);try{return f()}finally{endOperation(cm)}}function operation(cm,f){return function(){if(cm.curOp)return f.apply(cm,arguments);startOperation(cm);try{return f.apply(cm,arguments)}finally{endOperation(cm)}}}function methodOp(f){return function(){if(this.curOp)return f.apply(this,arguments);startOperation(this);try{return f.apply(this,arguments)}finally{endOperation(this)}}}function docMethodOp(f){return function(){var cm=this.cm;if(!cm||cm.curOp)return f.apply(this,arguments);startOperation(cm);try{return f.apply(this,arguments)}finally{endOperation(cm)}}}function regChange(cm,from,to,lendiff){null==from&&(from=cm.doc.first),null==to&&(to=cm.doc.first+cm.doc.size),lendiff||(lendiff=0);var display=cm.display;if(lendiff&&to<display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>from)&&(display.updateLineNumbers=from),cm.curOp.viewChanged=!0,from>=display.viewTo)sawCollapsedSpans&&visualLineNo(cm.doc,from)<display.viewTo&&resetView(cm);else if(to<=display.viewFrom)sawCollapsedSpans&&visualLineEndNo(cm.doc,to+lendiff)>display.viewFrom?resetView(cm):(display.viewFrom+=lendiff,display.viewTo+=lendiff);else if(from<=display.viewFrom&&to>=display.viewTo)resetView(cm);else if(from<=display.viewFrom){var cut=viewCuttingPoint(cm,to,to+lendiff,1);cut?(display.view=display.view.slice(cut.index),display.viewFrom=cut.lineN,display.viewTo+=lendiff):resetView(cm)}else if(to>=display.viewTo){var cut$1=viewCuttingPoint(cm,from,from,-1);cut$1?(display.view=display.view.slice(0,cut$1.index),display.viewTo=cut$1.lineN):resetView(cm)}else{var cutTop=viewCuttingPoint(cm,from,from,-1),cutBot=viewCuttingPoint(cm,to,to+lendiff,1);cutTop&&cutBot?(display.view=display.view.slice(0,cutTop.index).concat(buildViewArray(cm,cutTop.lineN,cutBot.lineN)).concat(display.view.slice(cutBot.index)),display.viewTo+=lendiff):resetView(cm)}var ext=display.externalMeasured;ext&&(to<ext.lineN?ext.lineN+=lendiff:from<ext.lineN+ext.size&&(display.externalMeasured=null))}function regLineChange(cm,line,type){cm.curOp.viewChanged=!0;var display=cm.display,ext=cm.display.externalMeasured;if(ext&&line>=ext.lineN&&line<ext.lineN+ext.size&&(display.externalMeasured=null),!(line<display.viewFrom||line>=display.viewTo)){var lineView=display.view[findViewIndex(cm,line)];if(null!=lineView.node){var arr=lineView.changes||(lineView.changes=[]);-1==indexOf(arr,type)&&arr.push(type)}}}function resetView(cm){cm.display.viewFrom=cm.display.viewTo=cm.doc.first,cm.display.view=[],cm.display.viewOffset=0}function viewCuttingPoint(cm,oldN,newN,dir){var diff,index=findViewIndex(cm,oldN),view=cm.display.view;if(!sawCollapsedSpans||newN==cm.doc.first+cm.doc.size)return{index:index,lineN:newN};for(var n=cm.display.viewFrom,i=0;i<index;i++)n+=view[i].size;if(n!=oldN){if(dir>0){if(index==view.length-1)return null;diff=n+view[index].size-oldN,index++}else diff=n-oldN;oldN+=diff,newN+=diff}for(;visualLineNo(cm.doc,newN)!=newN;){if(index==(dir<0?0:view.length-1))return null;newN+=dir*view[index-(dir<0?1:0)].size,index+=dir}return{index:index,lineN:newN}}function adjustView(cm,from,to){var display=cm.display;0==display.view.length||from>=display.viewTo||to<=display.viewFrom?(display.view=buildViewArray(cm,from,to),display.viewFrom=from):(display.viewFrom>from?display.view=buildViewArray(cm,from,display.viewFrom).concat(display.view):display.viewFrom<from&&(display.view=display.view.slice(findViewIndex(cm,from))),display.viewFrom=from,display.viewTo<to?display.view=display.view.concat(buildViewArray(cm,display.viewTo,to)):display.viewTo>to&&(display.view=display.view.slice(0,findViewIndex(cm,to)))),display.viewTo=to}function countDirtyView(cm){for(var view=cm.display.view,dirty=0,i=0;i<view.length;i++){var lineView=view[i];lineView.hidden||lineView.node&&!lineView.changes||++dirty}return dirty}function startWorker(cm,time){cm.doc.highlightFrontier<cm.display.viewTo&&cm.state.highlight.set(time,bind(highlightWorker,cm))}function highlightWorker(cm){var doc=cm.doc;if(!(doc.highlightFrontier>=cm.display.viewTo)){var end=+new Date+cm.options.workTime,context=getContextBefore(cm,doc.highlightFrontier),changedLines=[];doc.iter(context.line,Math.min(doc.first+doc.size,cm.display.viewTo+500),function(line){if(context.line>=cm.display.viewFrom){var oldStyles=line.styles,resetState=line.text.length>cm.options.maxHighlightLength?copyState(doc.mode,context.state):null,highlighted=highlightLine(cm,line,context,!0);resetState&&(context.state=resetState),line.styles=highlighted.styles;var oldCls=line.styleClasses,newCls=highlighted.classes;newCls?line.styleClasses=newCls:oldCls&&(line.styleClasses=null);for(var ischange=!oldStyles||oldStyles.length!=line.styles.length||oldCls!=newCls&&(!oldCls||!newCls||oldCls.bgClass!=newCls.bgClass||oldCls.textClass!=newCls.textClass),i=0;!ischange&&i<oldStyles.length;++i)ischange=oldStyles[i]!=line.styles[i];ischange&&changedLines.push(context.line),line.stateAfter=context.save(),context.nextLine()}else line.text.length<=cm.options.maxHighlightLength&&processLine(cm,line.text,context),line.stateAfter=context.line%5==0?context.save():null,context.nextLine();if(+new Date>end)return startWorker(cm,cm.options.workDelay),!0}),doc.highlightFrontier=context.line,doc.modeFrontier=Math.max(doc.modeFrontier,context.line),changedLines.length&&runInOp(cm,function(){for(var i=0;i<changedLines.length;i++)regLineChange(cm,changedLines[i],"text")})}}function maybeClipScrollbars(cm){var display=cm.display;!display.scrollbarsClipped&&display.scroller.offsetWidth&&(display.nativeBarWidth=display.scroller.offsetWidth-display.scroller.clientWidth,display.heightForcer.style.height=scrollGap(cm)+"px",display.sizer.style.marginBottom=-display.nativeBarWidth+"px",display.sizer.style.borderRightWidth=scrollGap(cm)+"px",display.scrollbarsClipped=!0)}function selectionSnapshot(cm){if(cm.hasFocus())return null;var active=activeElt();if(!active||!contains(cm.display.lineDiv,active))return null;var result={activeElt:active};if(window.getSelection){var sel=window.getSelection();sel.anchorNode&&sel.extend&&contains(cm.display.lineDiv,sel.anchorNode)&&(result.anchorNode=sel.anchorNode,result.anchorOffset=sel.anchorOffset,result.focusNode=sel.focusNode,result.focusOffset=sel.focusOffset)}return result}function restoreSelection(snapshot){if(snapshot&&snapshot.activeElt&&snapshot.activeElt!=activeElt()&&(snapshot.activeElt.focus(),snapshot.anchorNode&&contains(document.body,snapshot.anchorNode)&&contains(document.body,snapshot.focusNode))){var sel=window.getSelection(),range$$1=document.createRange();range$$1.setEnd(snapshot.anchorNode,snapshot.anchorOffset),range$$1.collapse(!1),sel.removeAllRanges(),sel.addRange(range$$1),sel.extend(snapshot.focusNode,snapshot.focusOffset)}}function updateDisplayIfNeeded(cm,update){var display=cm.display,doc=cm.doc;if(update.editorIsHidden)return resetView(cm),!1;if(!update.force&&update.visible.from>=display.viewFrom&&update.visible.to<=display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo)&&display.renderedView==display.view&&0==countDirtyView(cm))return!1;maybeUpdateLineNumberWidth(cm)&&(resetView(cm),update.dims=getDimensions(cm));var end=doc.first+doc.size,from=Math.max(update.visible.from-cm.options.viewportMargin,doc.first),to=Math.min(end,update.visible.to+cm.options.viewportMargin);display.viewFrom<from&&from-display.viewFrom<20&&(from=Math.max(doc.first,display.viewFrom)),display.viewTo>to&&display.viewTo-to<20&&(to=Math.min(end,display.viewTo)),sawCollapsedSpans&&(from=visualLineNo(cm.doc,from),to=visualLineEndNo(cm.doc,to));var different=from!=display.viewFrom||to!=display.viewTo||display.lastWrapHeight!=update.wrapperHeight||display.lastWrapWidth!=update.wrapperWidth;adjustView(cm,from,to),display.viewOffset=heightAtLine(getLine(cm.doc,display.viewFrom)),cm.display.mover.style.top=display.viewOffset+"px";var toUpdate=countDirtyView(cm);if(!different&&0==toUpdate&&!update.force&&display.renderedView==display.view&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo))return!1;var selSnapshot=selectionSnapshot(cm);return toUpdate>4&&(display.lineDiv.style.display="none"),patchDisplay(cm,display.updateLineNumbers,update.dims),toUpdate>4&&(display.lineDiv.style.display=""),display.renderedView=display.view,restoreSelection(selSnapshot),removeChildren(display.cursorDiv),removeChildren(display.selectionDiv),display.gutters.style.height=display.sizer.style.minHeight=0,different&&(display.lastWrapHeight=update.wrapperHeight,display.lastWrapWidth=update.wrapperWidth,startWorker(cm,400)),display.updateLineNumbers=null,!0}function postUpdateDisplay(cm,update){for(var viewport=update.viewport,first=!0;(first&&cm.options.lineWrapping&&update.oldDisplayWidth!=displayWidth(cm)||(viewport&&null!=viewport.top&&(viewport={top:Math.min(cm.doc.height+paddingVert(cm.display)-displayHeight(cm),viewport.top)}),update.visible=visibleLines(cm.display,cm.doc,viewport),!(update.visible.from>=cm.display.viewFrom&&update.visible.to<=cm.display.viewTo)))&&updateDisplayIfNeeded(cm,update);first=!1){updateHeightsInViewport(cm);var barMeasure=measureForScrollbars(cm);updateSelection(cm),updateScrollbars(cm,barMeasure),setDocumentHeight(cm,barMeasure),update.force=!1}update.signal(cm,"update",cm),cm.display.viewFrom==cm.display.reportedViewFrom&&cm.display.viewTo==cm.display.reportedViewTo||(update.signal(cm,"viewportChange",cm,cm.display.viewFrom,cm.display.viewTo),cm.display.reportedViewFrom=cm.display.viewFrom,cm.display.reportedViewTo=cm.display.viewTo)}function updateDisplaySimple(cm,viewport){var update=new DisplayUpdate(cm,viewport);if(updateDisplayIfNeeded(cm,update)){updateHeightsInViewport(cm),postUpdateDisplay(cm,update);var barMeasure=measureForScrollbars(cm);updateSelection(cm),updateScrollbars(cm,barMeasure),setDocumentHeight(cm,barMeasure),update.finish()}}function patchDisplay(cm,updateNumbersFrom,dims){function rm(node){var next=node.nextSibling;return webkit&&mac&&cm.display.currentWheelTarget==node?node.style.display="none":node.parentNode.removeChild(node),next}for(var display=cm.display,lineNumbers=cm.options.lineNumbers,container=display.lineDiv,cur=container.firstChild,view=display.view,lineN=display.viewFrom,i=0;i<view.length;i++){var lineView=view[i];if(lineView.hidden);else if(lineView.node&&lineView.node.parentNode==container){for(;cur!=lineView.node;)cur=rm(cur);var updateNumber=lineNumbers&&null!=updateNumbersFrom&&updateNumbersFrom<=lineN&&lineView.lineNumber;lineView.changes&&(indexOf(lineView.changes,"gutter")>-1&&(updateNumber=!1),updateLineForChanges(cm,lineView,lineN,dims)),updateNumber&&(removeChildren(lineView.lineNumber),lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options,lineN)))),cur=lineView.node.nextSibling}else{var node=buildLineElement(cm,lineView,lineN,dims);container.insertBefore(node,cur)}lineN+=lineView.size}for(;cur;)cur=rm(cur)}function updateGutterSpace(cm){var width=cm.display.gutters.offsetWidth;cm.display.sizer.style.marginLeft=width+"px"}function setDocumentHeight(cm,measure){cm.display.sizer.style.minHeight=measure.docHeight+"px",cm.display.heightForcer.style.top=measure.docHeight+"px",cm.display.gutters.style.height=measure.docHeight+cm.display.barHeight+scrollGap(cm)+"px"}function updateGutters(cm){var gutters=cm.display.gutters,specs=cm.options.gutters;removeChildren(gutters);for(var i=0;i<specs.length;++i){var gutterClass=specs[i],gElt=gutters.appendChild(elt("div",null,"CodeMirror-gutter "+gutterClass));"CodeMirror-linenumbers"==gutterClass&&(cm.display.lineGutter=gElt,gElt.style.width=(cm.display.lineNumWidth||1)+"px")}gutters.style.display=i?"":"none",updateGutterSpace(cm)}function setGuttersForLineNumbers(options){var found=indexOf(options.gutters,"CodeMirror-linenumbers");-1==found&&options.lineNumbers?options.gutters=options.gutters.concat(["CodeMirror-linenumbers"]):found>-1&&!options.lineNumbers&&(options.gutters=options.gutters.slice(0),options.gutters.splice(found,1))}function wheelEventDelta(e){var dx=e.wheelDeltaX,dy=e.wheelDeltaY;return null==dx&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(dx=e.detail),null==dy&&e.detail&&e.axis==e.VERTICAL_AXIS?dy=e.detail:null==dy&&(dy=e.wheelDelta),{x:dx,y:dy}}function wheelEventPixels(e){var delta=wheelEventDelta(e);return delta.x*=wheelPixelsPerUnit,delta.y*=wheelPixelsPerUnit,delta}function onScrollWheel(cm,e){var delta=wheelEventDelta(e),dx=delta.x,dy=delta.y,display=cm.display,scroll=display.scroller,canScrollX=scroll.scrollWidth>scroll.clientWidth,canScrollY=scroll.scrollHeight>scroll.clientHeight;if(dx&&canScrollX||dy&&canScrollY){if(dy&&mac&&webkit)outer:for(var cur=e.target,view=display.view;cur!=scroll;cur=cur.parentNode)for(var i=0;i<view.length;i++)if(view[i].node==cur){cm.display.currentWheelTarget=cur;break outer}if(dx&&!gecko&&!presto&&null!=wheelPixelsPerUnit)return dy&&canScrollY&&updateScrollTop(cm,Math.max(0,scroll.scrollTop+dy*wheelPixelsPerUnit)),setScrollLeft(cm,Math.max(0,scroll.scrollLeft+dx*wheelPixelsPerUnit)),(!dy||dy&&canScrollY)&&e_preventDefault(e),void(display.wheelStartX=null);if(dy&&null!=wheelPixelsPerUnit){var pixels=dy*wheelPixelsPerUnit,top=cm.doc.scrollTop,bot=top+display.wrapper.clientHeight;pixels<0?top=Math.max(0,top+pixels-50):bot=Math.min(cm.doc.height,bot+pixels+50),updateDisplaySimple(cm,{top:top,bottom:bot})}wheelSamples<20&&(null==display.wheelStartX?(display.wheelStartX=scroll.scrollLeft,display.wheelStartY=scroll.scrollTop,display.wheelDX=dx,display.wheelDY=dy,setTimeout(function(){if(null!=display.wheelStartX){var movedX=scroll.scrollLeft-display.wheelStartX,movedY=scroll.scrollTop-display.wheelStartY,sample=movedY&&display.wheelDY&&movedY/display.wheelDY||movedX&&display.wheelDX&&movedX/display.wheelDX;display.wheelStartX=display.wheelStartY=null,sample&&(wheelPixelsPerUnit=(wheelPixelsPerUnit*wheelSamples+sample)/(wheelSamples+1),++wheelSamples)}},200)):(display.wheelDX+=dx,display.wheelDY+=dy))}}function normalizeSelection(ranges,primIndex){var prim=ranges[primIndex];ranges.sort(function(a,b){return cmp(a.from(),b.from())}),primIndex=indexOf(ranges,prim);for(var i=1;i<ranges.length;i++){var cur=ranges[i],prev=ranges[i-1];if(cmp(prev.to(),cur.from())>=0){var from=minPos(prev.from(),cur.from()),to=maxPos(prev.to(),cur.to()),inv=prev.empty()?cur.from()==cur.head:prev.from()==prev.head;i<=primIndex&&--primIndex,ranges.splice(--i,2,new Range(inv?to:from,inv?from:to))}}return new Selection(ranges,primIndex)}function simpleSelection(anchor,head){return new Selection([new Range(anchor,head||anchor)],0)}function changeEnd(change){return change.text?Pos(change.from.line+change.text.length-1,lst(change.text).length+(1==change.text.length?change.from.ch:0)):change.to}function adjustForChange(pos,change){if(cmp(pos,change.from)<0)return pos;if(cmp(pos,change.to)<=0)return changeEnd(change);var line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch;return pos.line==change.to.line&&(ch+=changeEnd(change).ch-change.to.ch),Pos(line,ch)}function computeSelAfterChange(doc,change){for(var out=[],i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i];out.push(new Range(adjustForChange(range.anchor,change),adjustForChange(range.head,change)))}return normalizeSelection(out,doc.sel.primIndex)}function offsetPos(pos,old,nw){return pos.line==old.line?Pos(nw.line,pos.ch-old.ch+nw.ch):Pos(nw.line+(pos.line-old.line),pos.ch)}function computeReplacedSel(doc,changes,hint){for(var out=[],oldPrev=Pos(doc.first,0),newPrev=oldPrev,i=0;i<changes.length;i++){var change=changes[i],from=offsetPos(change.from,oldPrev,newPrev),to=offsetPos(changeEnd(change),oldPrev,newPrev);if(oldPrev=change.to,newPrev=to,"around"==hint){var range=doc.sel.ranges[i],inv=cmp(range.head,range.anchor)<0;out[i]=new Range(inv?to:from,inv?from:to)}else out[i]=new Range(from,from)}return new Selection(out,doc.sel.primIndex)}function loadMode(cm){cm.doc.mode=getMode(cm.options,cm.doc.modeOption),resetModeState(cm)}function resetModeState(cm){cm.doc.iter(function(line){line.stateAfter&&(line.stateAfter=null),line.styles&&(line.styles=null)}),cm.doc.modeFrontier=cm.doc.highlightFrontier=cm.doc.first,startWorker(cm,100),cm.state.modeGen++,cm.curOp&®Change(cm)}function isWholeLineUpdate(doc,change){return 0==change.from.ch&&0==change.to.ch&&""==lst(change.text)&&(!doc.cm||doc.cm.options.wholeLineUpdateBefore)}function updateDoc(doc,change,markedSpans,estimateHeight$$1){function spansFor(n){return markedSpans?markedSpans[n]:null}function update(line,text,spans){updateLine(line,text,spans,estimateHeight$$1),signalLater(line,"change",line,change)}function linesFor(start,end){for(var result=[],i=start;i<end;++i)result.push(new Line(text[i],spansFor(i),estimateHeight$$1));return result}var from=change.from,to=change.to,text=change.text,firstLine=getLine(doc,from.line),lastLine=getLine(doc,to.line),lastText=lst(text),lastSpans=spansFor(text.length-1),nlines=to.line-from.line;if(change.full)doc.insert(0,linesFor(0,text.length)),doc.remove(text.length,doc.size-text.length);else if(isWholeLineUpdate(doc,change)){var added=linesFor(0,text.length-1);update(lastLine,lastLine.text,lastSpans),nlines&&doc.remove(from.line,nlines),added.length&&doc.insert(from.line,added)}else if(firstLine==lastLine)if(1==text.length)update(firstLine,firstLine.text.slice(0,from.ch)+lastText+firstLine.text.slice(to.ch),lastSpans);else{var added$1=linesFor(1,text.length-1);added$1.push(new Line(lastText+firstLine.text.slice(to.ch),lastSpans,estimateHeight$$1)),update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)),doc.insert(from.line+1,added$1)}else if(1==text.length)update(firstLine,firstLine.text.slice(0,from.ch)+text[0]+lastLine.text.slice(to.ch),spansFor(0)),doc.remove(from.line+1,nlines);else{update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)),update(lastLine,lastText+lastLine.text.slice(to.ch),lastSpans);var added$2=linesFor(1,text.length-1);nlines>1&&doc.remove(from.line+1,nlines-1),doc.insert(from.line+1,added$2)}signalLater(doc,"change",doc,change)}function linkedDocs(doc,f,sharedHistOnly){function propagate(doc,skip,sharedHist){if(doc.linked)for(var i=0;i<doc.linked.length;++i){var rel=doc.linked[i];if(rel.doc!=skip){var shared=sharedHist&&rel.sharedHist;sharedHistOnly&&!shared||(f(rel.doc,shared),propagate(rel.doc,doc,shared))}}}propagate(doc,null,!0)}function attachDoc(cm,doc){if(doc.cm)throw new Error("This document is already in use.");cm.doc=doc,doc.cm=cm,estimateLineHeights(cm),loadMode(cm),setDirectionClass(cm),cm.options.lineWrapping||findMaxLine(cm),cm.options.mode=doc.modeOption,regChange(cm)}function setDirectionClass(cm){("rtl"==cm.doc.direction?addClass:rmClass)(cm.display.lineDiv,"CodeMirror-rtl")}function directionChanged(cm){runInOp(cm,function(){setDirectionClass(cm),regChange(cm)})}function History(startGen){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=this.lastSelOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=startGen||1}function historyChangeFromChange(doc,change){var histChange={from:copyPos(change.from),to:changeEnd(change),text:getBetween(doc,change.from,change.to)};return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1),linkedDocs(doc,function(doc){return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1)},!0),histChange}function clearSelectionEvents(array){for(;array.length&&lst(array).ranges;)array.pop()}function lastChangeEvent(hist,force){return force?(clearSelectionEvents(hist.done),lst(hist.done)):hist.done.length&&!lst(hist.done).ranges?lst(hist.done):hist.done.length>1&&!hist.done[hist.done.length-2].ranges?(hist.done.pop(),lst(hist.done)):void 0}function addChangeToHistory(doc,change,selAfter,opId){var hist=doc.history;hist.undone.length=0;var cur,last,time=+new Date;if((hist.lastOp==opId||hist.lastOrigin==change.origin&&change.origin&&("+"==change.origin.charAt(0)&&doc.cm&&hist.lastModTime>time-doc.cm.options.historyEventDelay||"*"==change.origin.charAt(0)))&&(cur=lastChangeEvent(hist,hist.lastOp==opId)))last=lst(cur.changes),0==cmp(change.from,change.to)&&0==cmp(change.from,last.to)?last.to=changeEnd(change):cur.changes.push(historyChangeFromChange(doc,change));else{var before=lst(hist.done);for(before&&before.ranges||pushSelectionToHistory(doc.sel,hist.done),cur={changes:[historyChangeFromChange(doc,change)],generation:hist.generation},hist.done.push(cur);hist.done.length>hist.undoDepth;)hist.done.shift(),hist.done[0].ranges||hist.done.shift()}hist.done.push(selAfter),hist.generation=++hist.maxGeneration,hist.lastModTime=hist.lastSelTime=time,hist.lastOp=hist.lastSelOp=opId,hist.lastOrigin=hist.lastSelOrigin=change.origin,last||signal(doc,"historyAdded")}function selectionEventCanBeMerged(doc,origin,prev,sel){var ch=origin.charAt(0);return"*"==ch||"+"==ch&&prev.ranges.length==sel.ranges.length&&prev.somethingSelected()==sel.somethingSelected()&&new Date-doc.history.lastSelTime<=(doc.cm?doc.cm.options.historyEventDelay:500)}function addSelectionToHistory(doc,sel,opId,options){var hist=doc.history,origin=options&&options.origin;opId==hist.lastSelOp||origin&&hist.lastSelOrigin==origin&&(hist.lastModTime==hist.lastSelTime&&hist.lastOrigin==origin||selectionEventCanBeMerged(doc,origin,lst(hist.done),sel))?hist.done[hist.done.length-1]=sel:pushSelectionToHistory(sel,hist.done),hist.lastSelTime=+new Date,hist.lastSelOrigin=origin,hist.lastSelOp=opId,options&&!1!==options.clearRedo&&clearSelectionEvents(hist.undone)}function pushSelectionToHistory(sel,dest){var top=lst(dest);top&&top.ranges&&top.equals(sel)||dest.push(sel)}function attachLocalSpans(doc,change,from,to){var existing=change["spans_"+doc.id],n=0;doc.iter(Math.max(doc.first,from),Math.min(doc.first+doc.size,to),function(line){line.markedSpans&&((existing||(existing=change["spans_"+doc.id]={}))[n]=line.markedSpans),++n})}function removeClearedSpans(spans){if(!spans)return null;for(var out,i=0;i<spans.length;++i)spans[i].marker.explicitlyCleared?out||(out=spans.slice(0,i)):out&&out.push(spans[i]);return out?out.length?out:null:spans}function getOldSpans(doc,change){var found=change["spans_"+doc.id];if(!found)return null;for(var nw=[],i=0;i<change.text.length;++i)nw.push(removeClearedSpans(found[i]));return nw}function mergeOldSpans(doc,change){var old=getOldSpans(doc,change),stretched=stretchSpansOverChange(doc,change);if(!old)return stretched;if(!stretched)return old;for(var i=0;i<old.length;++i){var oldCur=old[i],stretchCur=stretched[i];if(oldCur&&stretchCur)spans:for(var j=0;j<stretchCur.length;++j){for(var span=stretchCur[j],k=0;k<oldCur.length;++k)if(oldCur[k].marker==span.marker)continue spans;oldCur.push(span)}else stretchCur&&(old[i]=stretchCur)}return old}function copyHistoryArray(events,newGroup,instantiateSel){for(var copy=[],i=0;i<events.length;++i){var event=events[i];if(event.ranges)copy.push(instantiateSel?Selection.prototype.deepCopy.call(event):event);else{var changes=event.changes,newChanges=[];copy.push({changes:newChanges});for(var j=0;j<changes.length;++j){var change=changes[j],m=void 0;if(newChanges.push({from:change.from,to:change.to,text:change.text}),newGroup)for(var prop in change)(m=prop.match(/^spans_(\d+)$/))&&indexOf(newGroup,Number(m[1]))>-1&&(lst(newChanges)[prop]=change[prop],delete change[prop])}}}return copy}function extendRange(range,head,other,extend){if(extend){var anchor=range.anchor;if(other){var posBefore=cmp(head,anchor)<0;posBefore!=cmp(other,anchor)<0?(anchor=head,head=other):posBefore!=cmp(head,other)<0&&(head=other)}return new Range(anchor,head)}return new Range(other||head,head)}function extendSelection(doc,head,other,options,extend){null==extend&&(extend=doc.cm&&(doc.cm.display.shift||doc.extend)),setSelection(doc,new Selection([extendRange(doc.sel.primary(),head,other,extend)],0),options)}function extendSelections(doc,heads,options){for(var out=[],extend=doc.cm&&(doc.cm.display.shift||doc.extend),i=0;i<doc.sel.ranges.length;i++)out[i]=extendRange(doc.sel.ranges[i],heads[i],null,extend);setSelection(doc,normalizeSelection(out,doc.sel.primIndex),options)}function replaceOneSelection(doc,i,range,options){var ranges=doc.sel.ranges.slice(0);ranges[i]=range,setSelection(doc,normalizeSelection(ranges,doc.sel.primIndex),options)}function setSimpleSelection(doc,anchor,head,options){setSelection(doc,simpleSelection(anchor,head),options)}function filterSelectionChange(doc,sel,options){var obj={ranges:sel.ranges,update:function(ranges){var this$1=this;this.ranges=[];for(var i=0;i<ranges.length;i++)this$1.ranges[i]=new Range(clipPos(doc,ranges[i].anchor),clipPos(doc,ranges[i].head))},origin:options&&options.origin};return signal(doc,"beforeSelectionChange",doc,obj),doc.cm&&signal(doc.cm,"beforeSelectionChange",doc.cm,obj),obj.ranges!=sel.ranges?normalizeSelection(obj.ranges,obj.ranges.length-1):sel}function setSelectionReplaceHistory(doc,sel,options){var done=doc.history.done,last=lst(done);last&&last.ranges?(done[done.length-1]=sel,setSelectionNoUndo(doc,sel,options)):setSelection(doc,sel,options)}function setSelection(doc,sel,options){setSelectionNoUndo(doc,sel,options),addSelectionToHistory(doc,doc.sel,doc.cm?doc.cm.curOp.id:NaN,options)}function setSelectionNoUndo(doc,sel,options){(hasHandler(doc,"beforeSelectionChange")||doc.cm&&hasHandler(doc.cm,"beforeSelectionChange"))&&(sel=filterSelectionChange(doc,sel,options)),setSelectionInner(doc,skipAtomicInSelection(doc,sel,options&&options.bias||(cmp(sel.primary().head,doc.sel.primary().head)<0?-1:1),!0)),options&&!1===options.scroll||!doc.cm||ensureCursorVisible(doc.cm)}function setSelectionInner(doc,sel){sel.equals(doc.sel)||(doc.sel=sel,doc.cm&&(doc.cm.curOp.updateInput=doc.cm.curOp.selectionChanged=!0,signalCursorActivity(doc.cm)),signalLater(doc,"cursorActivity",doc))}function reCheckSelection(doc){setSelectionInner(doc,skipAtomicInSelection(doc,doc.sel,null,!1))}function skipAtomicInSelection(doc,sel,bias,mayClear){for(var out,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i],old=sel.ranges.length==doc.sel.ranges.length&&doc.sel.ranges[i],newAnchor=skipAtomic(doc,range.anchor,old&&old.anchor,bias,mayClear),newHead=skipAtomic(doc,range.head,old&&old.head,bias,mayClear);(out||newAnchor!=range.anchor||newHead!=range.head)&&(out||(out=sel.ranges.slice(0,i)),out[i]=new Range(newAnchor,newHead))}return out?normalizeSelection(out,sel.primIndex):sel}function skipAtomicInner(doc,pos,oldPos,dir,mayClear){var line=getLine(doc,pos.line);if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var sp=line.markedSpans[i],m=sp.marker;if((null==sp.from||(m.inclusiveLeft?sp.from<=pos.ch:sp.from<pos.ch))&&(null==sp.to||(m.inclusiveRight?sp.to>=pos.ch:sp.to>pos.ch))){if(mayClear&&(signal(m,"beforeCursorEnter"),m.explicitlyCleared)){if(line.markedSpans){--i;continue}break}if(!m.atomic)continue;if(oldPos){var near=m.find(dir<0?1:-1),diff=void 0;if((dir<0?m.inclusiveRight:m.inclusiveLeft)&&(near=movePos(doc,near,-dir,near&&near.line==pos.line?line:null)),near&&near.line==pos.line&&(diff=cmp(near,oldPos))&&(dir<0?diff<0:diff>0))return skipAtomicInner(doc,near,pos,dir,mayClear)}var far=m.find(dir<0?-1:1);return(dir<0?m.inclusiveLeft:m.inclusiveRight)&&(far=movePos(doc,far,dir,far.line==pos.line?line:null)),far?skipAtomicInner(doc,far,pos,dir,mayClear):null}}return pos}function skipAtomic(doc,pos,oldPos,bias,mayClear){var dir=bias||1,found=skipAtomicInner(doc,pos,oldPos,dir,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,dir,!0)||skipAtomicInner(doc,pos,oldPos,-dir,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,-dir,!0);return found||(doc.cantEdit=!0,Pos(doc.first,0))}function movePos(doc,pos,dir,line){return dir<0&&0==pos.ch?pos.line>doc.first?clipPos(doc,Pos(pos.line-1)):null:dir>0&&pos.ch==(line||getLine(doc,pos.line)).text.length?pos.line<doc.first+doc.size-1?Pos(pos.line+1,0):null:new Pos(pos.line,pos.ch+dir)}function selectAll(cm){cm.setSelection(Pos(cm.firstLine(),0),Pos(cm.lastLine()),sel_dontScroll)}function filterChange(doc,change,update){var obj={canceled:!1,from:change.from,to:change.to,text:change.text,origin:change.origin,cancel:function(){return obj.canceled=!0}};return update&&(obj.update=function(from,to,text,origin){from&&(obj.from=clipPos(doc,from)),to&&(obj.to=clipPos(doc,to)),text&&(obj.text=text),void 0!==origin&&(obj.origin=origin)}),signal(doc,"beforeChange",doc,obj),doc.cm&&signal(doc.cm,"beforeChange",doc.cm,obj),obj.canceled?null:{from:obj.from,to:obj.to,text:obj.text,origin:obj.origin}}function makeChange(doc,change,ignoreReadOnly){if(doc.cm){if(!doc.cm.curOp)return operation(doc.cm,makeChange)(doc,change,ignoreReadOnly);if(doc.cm.state.suppressEdits)return}if(!(hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange"))||(change=filterChange(doc,change,!0))){var split=sawReadOnlySpans&&!ignoreReadOnly&&removeReadOnlyRanges(doc,change.from,change.to);if(split)for(var i=split.length-1;i>=0;--i)makeChangeInner(doc,{from:split[i].from,to:split[i].to,text:i?[""]:change.text});else makeChangeInner(doc,change)}}function makeChangeInner(doc,change){if(1!=change.text.length||""!=change.text[0]||0!=cmp(change.from,change.to)){var selAfter=computeSelAfterChange(doc,change);addChangeToHistory(doc,change,selAfter,doc.cm?doc.cm.curOp.id:NaN),makeChangeSingleDoc(doc,change,selAfter,stretchSpansOverChange(doc,change));var rebased=[];linkedDocs(doc,function(doc,sharedHist){sharedHist||-1!=indexOf(rebased,doc.history)||(rebaseHist(doc.history,change),rebased.push(doc.history)),makeChangeSingleDoc(doc,change,null,stretchSpansOverChange(doc,change))})}}function makeChangeFromHistory(doc,type,allowSelectionOnly){if(!doc.cm||!doc.cm.state.suppressEdits||allowSelectionOnly){for(var event,hist=doc.history,selAfter=doc.sel,source="undo"==type?hist.done:hist.undone,dest="undo"==type?hist.undone:hist.done,i=0;i<source.length&&(event=source[i],allowSelectionOnly?!event.ranges||event.equals(doc.sel):event.ranges);i++);if(i!=source.length){for(hist.lastOrigin=hist.lastSelOrigin=null;(event=source.pop()).ranges;){if(pushSelectionToHistory(event,dest),allowSelectionOnly&&!event.equals(doc.sel))return void setSelection(doc,event,{clearRedo:!1});selAfter=event}var antiChanges=[];pushSelectionToHistory(selAfter,dest),dest.push({changes:antiChanges,generation:hist.generation}),hist.generation=event.generation||++hist.maxGeneration;for(var filter=hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange"),i$1=event.changes.length-1;i$1>=0;--i$1){var returned=function(i){var change=event.changes[i];if(change.origin=type,filter&&!filterChange(doc,change,!1))return source.length=0,{};antiChanges.push(historyChangeFromChange(doc,change));var after=i?computeSelAfterChange(doc,change):lst(source);makeChangeSingleDoc(doc,change,after,mergeOldSpans(doc,change)),!i&&doc.cm&&doc.cm.scrollIntoView({from:change.from,to:changeEnd(change)});var rebased=[];linkedDocs(doc,function(doc,sharedHist){sharedHist||-1!=indexOf(rebased,doc.history)||(rebaseHist(doc.history,change),rebased.push(doc.history)),makeChangeSingleDoc(doc,change,null,mergeOldSpans(doc,change))})}(i$1);if(returned)return returned.v}}}}function shiftDoc(doc,distance){if(0!=distance&&(doc.first+=distance,doc.sel=new Selection(map(doc.sel.ranges,function(range){return new Range(Pos(range.anchor.line+distance,range.anchor.ch),Pos(range.head.line+distance,range.head.ch))}),doc.sel.primIndex),doc.cm)){regChange(doc.cm,doc.first,doc.first-distance,distance);for(var d=doc.cm.display,l=d.viewFrom;l<d.viewTo;l++)regLineChange(doc.cm,l,"gutter")}}function makeChangeSingleDoc(doc,change,selAfter,spans){if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,makeChangeSingleDoc)(doc,change,selAfter,spans);if(change.to.line<doc.first)shiftDoc(doc,change.text.length-1-(change.to.line-change.from.line));else if(!(change.from.line>doc.lastLine())){if(change.from.line<doc.first){var shift=change.text.length-1-(doc.first-change.from.line);shiftDoc(doc,shift),change={from:Pos(doc.first,0),to:Pos(change.to.line+shift,change.to.ch),text:[lst(change.text)],origin:change.origin}}var last=doc.lastLine();change.to.line>last&&(change={from:change.from,to:Pos(last,getLine(doc,last).text.length),text:[change.text[0]],origin:change.origin}),change.removed=getBetween(doc,change.from,change.to),selAfter||(selAfter=computeSelAfterChange(doc,change)),doc.cm?makeChangeSingleDocInEditor(doc.cm,change,spans):updateDoc(doc,change,spans),setSelectionNoUndo(doc,selAfter,sel_dontScroll)}}function makeChangeSingleDocInEditor(cm,change,spans){var doc=cm.doc,display=cm.display,from=change.from,to=change.to,recomputeMaxLength=!1,checkWidthStart=from.line;cm.options.lineWrapping||(checkWidthStart=lineNo(visualLine(getLine(doc,from.line))),doc.iter(checkWidthStart,to.line+1,function(line){if(line==display.maxLine)return recomputeMaxLength=!0,!0})),doc.sel.contains(change.from,change.to)>-1&&signalCursorActivity(cm),updateDoc(doc,change,spans,estimateHeight(cm)),cm.options.lineWrapping||(doc.iter(checkWidthStart,from.line+change.text.length,function(line){var len=lineLength(line);len>display.maxLineLength&&(display.maxLine=line,display.maxLineLength=len,display.maxLineChanged=!0,recomputeMaxLength=!1)}),recomputeMaxLength&&(cm.curOp.updateMaxLine=!0)),retreatFrontier(doc,from.line),startWorker(cm,400);var lendiff=change.text.length-(to.line-from.line)-1;change.full?regChange(cm):from.line!=to.line||1!=change.text.length||isWholeLineUpdate(cm.doc,change)?regChange(cm,from.line,to.line+1,lendiff):regLineChange(cm,from.line,"text");var changesHandler=hasHandler(cm,"changes"),changeHandler=hasHandler(cm,"change");if(changeHandler||changesHandler){var obj={from:from,to:to,text:change.text,removed:change.removed,origin:change.origin};changeHandler&&signalLater(cm,"change",cm,obj),changesHandler&&(cm.curOp.changeObjs||(cm.curOp.changeObjs=[])).push(obj)}cm.display.selForContextMenu=null}function replaceRange(doc,code,from,to,origin){if(to||(to=from),cmp(to,from)<0){var tmp=to;to=from,from=tmp}"string"==typeof code&&(code=doc.splitLines(code)),makeChange(doc,{from:from,to:to,text:code,origin:origin})}function rebaseHistSelSingle(pos,from,to,diff){to<pos.line?pos.line+=diff:from<pos.line&&(pos.line=from,pos.ch=0)}function rebaseHistArray(array,from,to,diff){for(var i=0;i<array.length;++i){var sub=array[i],ok=!0;if(sub.ranges){sub.copied||((sub=array[i]=sub.deepCopy()).copied=!0);for(var j=0;j<sub.ranges.length;j++)rebaseHistSelSingle(sub.ranges[j].anchor,from,to,diff),rebaseHistSelSingle(sub.ranges[j].head,from,to,diff)}else{for(var j$1=0;j$1<sub.changes.length;++j$1){var cur=sub.changes[j$1];if(to<cur.from.line)cur.from=Pos(cur.from.line+diff,cur.from.ch),cur.to=Pos(cur.to.line+diff,cur.to.ch);else if(from<=cur.to.line){ok=!1;break}}ok||(array.splice(0,i+1),i=0)}}}function rebaseHist(hist,change){var from=change.from.line,to=change.to.line,diff=change.text.length-(to-from)-1;rebaseHistArray(hist.done,from,to,diff),rebaseHistArray(hist.undone,from,to,diff)}function changeLine(doc,handle,changeType,op){var no=handle,line=handle;return"number"==typeof handle?line=getLine(doc,clipLine(doc,handle)):no=lineNo(handle),null==no?null:(op(line,no)&&doc.cm&®LineChange(doc.cm,no,changeType),line)}function LeafChunk(lines){var this$1=this;this.lines=lines,this.parent=null;for(var height=0,i=0;i<lines.length;++i)lines[i].parent=this$1,height+=lines[i].height;this.height=height}function BranchChunk(children){var this$1=this;this.children=children;for(var size=0,height=0,i=0;i<children.length;++i){var ch=children[i];size+=ch.chunkSize(),height+=ch.height,ch.parent=this$1}this.size=size,this.height=height,this.parent=null}function adjustScrollWhenAboveVisible(cm,line,diff){heightAtLine(line)<(cm.curOp&&cm.curOp.scrollTop||cm.doc.scrollTop)&&addToScrollTop(cm,diff)}function addLineWidget(doc,handle,node,options){var widget=new LineWidget(doc,node,options),cm=doc.cm;return cm&&widget.noHScroll&&(cm.display.alignWidgets=!0),changeLine(doc,handle,"widget",function(line){var widgets=line.widgets||(line.widgets=[]);if(null==widget.insertAt?widgets.push(widget):widgets.splice(Math.min(widgets.length-1,Math.max(0,widget.insertAt)),0,widget),widget.line=line,cm&&!lineIsHidden(doc,line)){var aboveVisible=heightAtLine(line)<doc.scrollTop;updateLineHeight(line,line.height+widgetHeight(widget)),aboveVisible&&addToScrollTop(cm,widget.height),cm.curOp.forceUpdate=!0}return!0}),signalLater(cm,"lineWidgetAdded",cm,widget,"number"==typeof handle?handle:lineNo(handle)),widget}function markText(doc,from,to,options,type){if(options&&options.shared)return markTextShared(doc,from,to,options,type);if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,markText)(doc,from,to,options,type);var marker=new TextMarker(doc,type),diff=cmp(from,to);if(options&©Obj(options,marker,!1),diff>0||0==diff&&!1!==marker.clearWhenEmpty)return marker;if(marker.replacedWith&&(marker.collapsed=!0,marker.widgetNode=eltP("span",[marker.replacedWith],"CodeMirror-widget"),options.handleMouseEvents||marker.widgetNode.setAttribute("cm-ignore-events","true"),options.insertLeft&&(marker.widgetNode.insertLeft=!0)),marker.collapsed){if(conflictingCollapsedRange(doc,from.line,from,to,marker)||from.line!=to.line&&conflictingCollapsedRange(doc,to.line,from,to,marker))throw new Error("Inserting collapsed marker partially overlapping an existing one");seeCollapsedSpans()}marker.addToHistory&&addChangeToHistory(doc,{from:from,to:to,origin:"markText"},doc.sel,NaN);var updateMaxLine,curLine=from.line,cm=doc.cm;if(doc.iter(curLine,to.line+1,function(line){cm&&marker.collapsed&&!cm.options.lineWrapping&&visualLine(line)==cm.display.maxLine&&(updateMaxLine=!0),marker.collapsed&&curLine!=from.line&&updateLineHeight(line,0),addMarkedSpan(line,new MarkedSpan(marker,curLine==from.line?from.ch:null,curLine==to.line?to.ch:null)),++curLine}),marker.collapsed&&doc.iter(from.line,to.line+1,function(line){lineIsHidden(doc,line)&&updateLineHeight(line,0)}),marker.clearOnEnter&&on(marker,"beforeCursorEnter",function(){return marker.clear()}),marker.readOnly&&(seeReadOnlySpans(),(doc.history.done.length||doc.history.undone.length)&&doc.clearHistory()),marker.collapsed&&(marker.id=++nextMarkerId,marker.atomic=!0),cm){if(updateMaxLine&&(cm.curOp.updateMaxLine=!0),marker.collapsed)regChange(cm,from.line,to.line+1);else if(marker.className||marker.title||marker.startStyle||marker.endStyle||marker.css)for(var i=from.line;i<=to.line;i++)regLineChange(cm,i,"text");marker.atomic&&reCheckSelection(cm.doc),signalLater(cm,"markerAdded",cm,marker)}return marker}function markTextShared(doc,from,to,options,type){(options=copyObj(options)).shared=!1;var markers=[markText(doc,from,to,options,type)],primary=markers[0],widget=options.widgetNode;return linkedDocs(doc,function(doc){widget&&(options.widgetNode=widget.cloneNode(!0)),markers.push(markText(doc,clipPos(doc,from),clipPos(doc,to),options,type));for(var i=0;i<doc.linked.length;++i)if(doc.linked[i].isParent)return;primary=lst(markers)}),new SharedTextMarker(markers,primary)}function findSharedMarkers(doc){return doc.findMarks(Pos(doc.first,0),doc.clipPos(Pos(doc.lastLine())),function(m){return m.parent})}function copySharedMarkers(doc,markers){for(var i=0;i<markers.length;i++){var marker=markers[i],pos=marker.find(),mFrom=doc.clipPos(pos.from),mTo=doc.clipPos(pos.to);if(cmp(mFrom,mTo)){var subMark=markText(doc,mFrom,mTo,marker.primary,marker.primary.type);marker.markers.push(subMark),subMark.parent=marker}}}function detachSharedMarkers(markers){for(var i=0;i<markers.length;i++)!function(i){var marker=markers[i],linked=[marker.primary.doc];linkedDocs(marker.primary.doc,function(d){return linked.push(d)});for(var j=0;j<marker.markers.length;j++){var subMarker=marker.markers[j];-1==indexOf(linked,subMarker.doc)&&(subMarker.parent=null,marker.markers.splice(j--,1))}}(i)}function onDrop(e){var cm=this;if(clearDragCursor(cm),!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e),ie&&(lastDrop=+new Date);var pos=posFromMouse(cm,e,!0),files=e.dataTransfer.files;if(pos&&!cm.isReadOnly())if(files&&files.length&&window.FileReader&&window.File)for(var n=files.length,text=Array(n),read=0,i=0;i<n;++i)!function(file,i){if(!cm.options.allowDropFileTypes||-1!=indexOf(cm.options.allowDropFileTypes,file.type)){var reader=new FileReader;reader.onload=operation(cm,function(){var content=reader.result;if(/[\x00-\x08\x0e-\x1f]{2}/.test(content)&&(content=""),text[i]=content,++read==n){var change={from:pos=clipPos(cm.doc,pos),to:pos,text:cm.doc.splitLines(text.join(cm.doc.lineSeparator())),origin:"paste"};makeChange(cm.doc,change),setSelectionReplaceHistory(cm.doc,simpleSelection(pos,changeEnd(change)))}}),reader.readAsText(file)}}(files[i],i);else{if(cm.state.draggingText&&cm.doc.sel.contains(pos)>-1)return cm.state.draggingText(e),void setTimeout(function(){return cm.display.input.focus()},20);try{var text$1=e.dataTransfer.getData("Text");if(text$1){var selected;if(cm.state.draggingText&&!cm.state.draggingText.copy&&(selected=cm.listSelections()),setSelectionNoUndo(cm.doc,simpleSelection(pos,pos)),selected)for(var i$1=0;i$1<selected.length;++i$1)replaceRange(cm.doc,"",selected[i$1].anchor,selected[i$1].head,"drag");cm.replaceSelection(text$1,"around","paste"),cm.display.input.focus()}}catch(e){}}}}function onDragStart(cm,e){if(ie&&(!cm.state.draggingText||+new Date-lastDrop<100))e_stop(e);else if(!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)&&(e.dataTransfer.setData("Text",cm.getSelection()),e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setDragImage&&!safari)){var img=elt("img",null,null,"position: fixed; left: 0; top: 0;");img.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",presto&&(img.width=img.height=1,cm.display.wrapper.appendChild(img),img._top=img.offsetTop),e.dataTransfer.setDragImage(img,0,0),presto&&img.parentNode.removeChild(img)}}function onDragOver(cm,e){var pos=posFromMouse(cm,e);if(pos){var frag=document.createDocumentFragment();drawSelectionCursor(cm,pos,frag),cm.display.dragCursor||(cm.display.dragCursor=elt("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),cm.display.lineSpace.insertBefore(cm.display.dragCursor,cm.display.cursorDiv)),removeChildrenAndAdd(cm.display.dragCursor,frag)}}function clearDragCursor(cm){cm.display.dragCursor&&(cm.display.lineSpace.removeChild(cm.display.dragCursor),cm.display.dragCursor=null)}function forEachCodeMirror(f){if(document.getElementsByClassName)for(var byClass=document.getElementsByClassName("CodeMirror"),i=0;i<byClass.length;i++){var cm=byClass[i].CodeMirror;cm&&f(cm)}}function ensureGlobalHandlers(){globalsRegistered||(registerGlobalHandlers(),globalsRegistered=!0)}function registerGlobalHandlers(){var resizeTimer;on(window,"resize",function(){null==resizeTimer&&(resizeTimer=setTimeout(function(){resizeTimer=null,forEachCodeMirror(onResize)},100))}),on(window,"blur",function(){return forEachCodeMirror(onBlur)})}function onResize(cm){var d=cm.display;d.lastWrapHeight==d.wrapper.clientHeight&&d.lastWrapWidth==d.wrapper.clientWidth||(d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null,d.scrollbarsClipped=!1,cm.setSize())}function normalizeKeyName(name){var parts=name.split(/-(?!$)/);name=parts[parts.length-1];for(var alt,ctrl,shift,cmd,i=0;i<parts.length-1;i++){var mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod))cmd=!0;else if(/^a(lt)?$/i.test(mod))alt=!0;else if(/^(c|ctrl|control)$/i.test(mod))ctrl=!0;else{if(!/^s(hift)?$/i.test(mod))throw new Error("Unrecognized modifier name: "+mod);shift=!0}}return alt&&(name="Alt-"+name),ctrl&&(name="Ctrl-"+name),cmd&&(name="Cmd-"+name),shift&&(name="Shift-"+name),name}function normalizeKeyMap(keymap){var copy={};for(var keyname in keymap)if(keymap.hasOwnProperty(keyname)){var value=keymap[keyname];if(/^(name|fallthrough|(de|at)tach)$/.test(keyname))continue;if("..."==value){delete keymap[keyname];continue}for(var keys=map(keyname.split(" "),normalizeKeyName),i=0;i<keys.length;i++){var val=void 0,name=void 0;i==keys.length-1?(name=keys.join(" "),val=value):(name=keys.slice(0,i+1).join(" "),val="...");var prev=copy[name];if(prev){if(prev!=val)throw new Error("Inconsistent bindings for "+name)}else copy[name]=val}delete keymap[keyname]}for(var prop in copy)keymap[prop]=copy[prop];return keymap}function lookupKey(key,map$$1,handle,context){var found=(map$$1=getKeyMap(map$$1)).call?map$$1.call(key,context):map$$1[key];if(!1===found)return"nothing";if("..."===found)return"multi";if(null!=found&&handle(found))return"handled";if(map$$1.fallthrough){if("[object Array]"!=Object.prototype.toString.call(map$$1.fallthrough))return lookupKey(key,map$$1.fallthrough,handle,context);for(var i=0;i<map$$1.fallthrough.length;i++){var result=lookupKey(key,map$$1.fallthrough[i],handle,context);if(result)return result}}}function isModifierKey(value){var name="string"==typeof value?value:keyNames[value.keyCode];return"Ctrl"==name||"Alt"==name||"Shift"==name||"Mod"==name}function addModifierNames(name,event,noShift){var base=name;return event.altKey&&"Alt"!=base&&(name="Alt-"+name),(flipCtrlCmd?event.metaKey:event.ctrlKey)&&"Ctrl"!=base&&(name="Ctrl-"+name),(flipCtrlCmd?event.ctrlKey:event.metaKey)&&"Cmd"!=base&&(name="Cmd-"+name),!noShift&&event.shiftKey&&"Shift"!=base&&(name="Shift-"+name),name}function keyName(event,noShift){if(presto&&34==event.keyCode&&event.char)return!1;var name=keyNames[event.keyCode];return null!=name&&!event.altGraphKey&&addModifierNames(name,event,noShift)}function getKeyMap(val){return"string"==typeof val?keyMap[val]:val}function deleteNearSelection(cm,compute){for(var ranges=cm.doc.sel.ranges,kill=[],i=0;i<ranges.length;i++){for(var toKill=compute(ranges[i]);kill.length&&cmp(toKill.from,lst(kill).to)<=0;){var replaced=kill.pop();if(cmp(replaced.from,toKill.from)<0){toKill.from=replaced.from;break}}kill.push(toKill)}runInOp(cm,function(){for(var i=kill.length-1;i>=0;i--)replaceRange(cm.doc,"",kill[i].from,kill[i].to,"+delete");ensureCursorVisible(cm)})}function lineStart(cm,lineN){var line=getLine(cm.doc,lineN),visual=visualLine(line);return visual!=line&&(lineN=lineNo(visual)),endOfLine(!0,cm,visual,lineN,1)}function lineEnd(cm,lineN){var line=getLine(cm.doc,lineN),visual=visualLineEnd(line);return visual!=line&&(lineN=lineNo(visual)),endOfLine(!0,cm,line,lineN,-1)}function lineStartSmart(cm,pos){var start=lineStart(cm,pos.line),line=getLine(cm.doc,start.line),order=getOrder(line,cm.doc.direction);if(!order||0==order[0].level){var firstNonWS=Math.max(0,line.text.search(/\S/)),inWS=pos.line==start.line&&pos.ch<=firstNonWS&&pos.ch;return Pos(start.line,inWS?0:firstNonWS,start.sticky)}return start}function doHandleBinding(cm,bound,dropShift){if("string"==typeof bound&&!(bound=commands[bound]))return!1;cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0),dropShift&&(cm.display.shift=!1),done=bound(cm)!=Pass}finally{cm.display.shift=prevShift,cm.state.suppressEdits=!1}return done}function lookupKeyForEditor(cm,name,handle){for(var i=0;i<cm.state.keyMaps.length;i++){var result=lookupKey(name,cm.state.keyMaps[i],handle,cm);if(result)return result}return cm.options.extraKeys&&lookupKey(name,cm.options.extraKeys,handle,cm)||lookupKey(name,cm.options.keyMap,handle,cm)}function dispatchKey(cm,name,e,handle){var seq=cm.state.keySeq;if(seq){if(isModifierKey(name))return"handled";stopSeq.set(50,function(){cm.state.keySeq==seq&&(cm.state.keySeq=null,cm.display.input.reset())}),name=seq+" "+name}var result=lookupKeyForEditor(cm,name,handle);return"multi"==result&&(cm.state.keySeq=name),"handled"==result&&signalLater(cm,"keyHandled",cm,name,e),"handled"!=result&&"multi"!=result||(e_preventDefault(e),restartBlink(cm)),seq&&!result&&/\'$/.test(name)?(e_preventDefault(e),!0):!!result}function handleKeyBinding(cm,e){var name=keyName(e,!0);return!!name&&(e.shiftKey&&!cm.state.keySeq?dispatchKey(cm,"Shift-"+name,e,function(b){return doHandleBinding(cm,b,!0)})||dispatchKey(cm,name,e,function(b){if("string"==typeof b?/^go[A-Z]/.test(b):b.motion)return doHandleBinding(cm,b)}):dispatchKey(cm,name,e,function(b){return doHandleBinding(cm,b)}))}function handleCharBinding(cm,e,ch){return dispatchKey(cm,"'"+ch+"'",e,function(b){return doHandleBinding(cm,b,!0)})}function onKeyDown(e){var cm=this;if(cm.curOp.focus=activeElt(),!signalDOMEvent(cm,e)){ie&&ie_version<11&&27==e.keyCode&&(e.returnValue=!1);var code=e.keyCode;cm.display.shift=16==code||e.shiftKey;var handled=handleKeyBinding(cm,e);presto&&(lastStoppedKey=handled?code:null,!handled&&88==code&&!hasCopyEvent&&(mac?e.metaKey:e.ctrlKey)&&cm.replaceSelection("",null,"cut")),18!=code||/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)||showCrossHair(cm)}}function showCrossHair(cm){function up(e){18!=e.keyCode&&e.altKey||(rmClass(lineDiv,"CodeMirror-crosshair"),off(document,"keyup",up),off(document,"mouseover",up))}var lineDiv=cm.display.lineDiv;addClass(lineDiv,"CodeMirror-crosshair"),on(document,"keyup",up),on(document,"mouseover",up)}function onKeyUp(e){16==e.keyCode&&(this.doc.sel.shift=!1),signalDOMEvent(this,e)}function onKeyPress(e){var cm=this;if(!(eventInWidget(cm.display,e)||signalDOMEvent(cm,e)||e.ctrlKey&&!e.altKey||mac&&e.metaKey)){var keyCode=e.keyCode,charCode=e.charCode;if(presto&&keyCode==lastStoppedKey)return lastStoppedKey=null,void e_preventDefault(e);if(!presto||e.which&&!(e.which<10)||!handleKeyBinding(cm,e)){var ch=String.fromCharCode(null==charCode?keyCode:charCode);"\b"!=ch&&(handleCharBinding(cm,e,ch)||cm.display.input.onKeyPress(e))}}}function clickRepeat(pos,button){var now=+new Date;return lastDoubleClick&&lastDoubleClick.compare(now,pos,button)?(lastClick=lastDoubleClick=null,"triple"):lastClick&&lastClick.compare(now,pos,button)?(lastDoubleClick=new PastClick(now,pos,button),lastClick=null,"double"):(lastClick=new PastClick(now,pos,button),lastDoubleClick=null,"single")}function onMouseDown(e){var cm=this,display=cm.display;if(!(signalDOMEvent(cm,e)||display.activeTouch&&display.input.supportsTouch()))if(display.input.ensurePolled(),display.shift=e.shiftKey,eventInWidget(display,e))webkit||(display.scroller.draggable=!1,setTimeout(function(){return display.scroller.draggable=!0},100));else if(!clickInGutter(cm,e)){var pos=posFromMouse(cm,e),button=e_button(e),repeat=pos?clickRepeat(pos,button):"single";window.focus(),1==button&&cm.state.selectingText&&cm.state.selectingText(e),pos&&handleMappedButton(cm,button,pos,repeat,e)||(1==button?pos?leftButtonDown(cm,pos,repeat,e):e_target(e)==display.scroller&&e_preventDefault(e):2==button?(pos&&extendSelection(cm.doc,pos),setTimeout(function(){return display.input.focus()},20)):3==button&&(captureRightClick?onContextMenu(cm,e):delayBlurEvent(cm)))}}function handleMappedButton(cm,button,pos,repeat,event){var name="Click";return"double"==repeat?name="Double"+name:"triple"==repeat&&(name="Triple"+name),name=(1==button?"Left":2==button?"Middle":"Right")+name,dispatchKey(cm,addModifierNames(name,event),event,function(bound){if("string"==typeof bound&&(bound=commands[bound]),!bound)return!1;var done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0),done=bound(cm,pos)!=Pass}finally{cm.state.suppressEdits=!1}return done})}function configureMouse(cm,repeat,event){var option=cm.getOption("configureMouse"),value=option?option(cm,repeat,event):{};if(null==value.unit){var rect=chromeOS?event.shiftKey&&event.metaKey:event.altKey;value.unit=rect?"rectangle":"single"==repeat?"char":"double"==repeat?"word":"line"}return(null==value.extend||cm.doc.extend)&&(value.extend=cm.doc.extend||event.shiftKey),null==value.addNew&&(value.addNew=mac?event.metaKey:event.ctrlKey),null==value.moveOnDrag&&(value.moveOnDrag=!(mac?event.altKey:event.ctrlKey)),value}function leftButtonDown(cm,pos,repeat,event){ie?setTimeout(bind(ensureFocus,cm),0):cm.curOp.focus=activeElt();var contained,behavior=configureMouse(cm,repeat,event),sel=cm.doc.sel;cm.options.dragDrop&&dragAndDrop&&!cm.isReadOnly()&&"single"==repeat&&(contained=sel.contains(pos))>-1&&(cmp((contained=sel.ranges[contained]).from(),pos)<0||pos.xRel>0)&&(cmp(contained.to(),pos)>0||pos.xRel<0)?leftButtonStartDrag(cm,event,pos,behavior):leftButtonSelect(cm,event,pos,behavior)}function leftButtonStartDrag(cm,event,pos,behavior){var display=cm.display,moved=!1,dragEnd=operation(cm,function(e){webkit&&(display.scroller.draggable=!1),cm.state.draggingText=!1,off(document,"mouseup",dragEnd),off(document,"mousemove",mouseMove),off(display.scroller,"dragstart",dragStart),off(display.scroller,"drop",dragEnd),moved||(e_preventDefault(e),behavior.addNew||extendSelection(cm.doc,pos,null,null,behavior.extend),webkit||ie&&9==ie_version?setTimeout(function(){document.body.focus(),display.input.focus()},20):display.input.focus())}),mouseMove=function(e2){moved=moved||Math.abs(event.clientX-e2.clientX)+Math.abs(event.clientY-e2.clientY)>=10},dragStart=function(){return moved=!0};webkit&&(display.scroller.draggable=!0),cm.state.draggingText=dragEnd,dragEnd.copy=!behavior.moveOnDrag,display.scroller.dragDrop&&display.scroller.dragDrop(),on(document,"mouseup",dragEnd),on(document,"mousemove",mouseMove),on(display.scroller,"dragstart",dragStart),on(display.scroller,"drop",dragEnd),delayBlurEvent(cm),setTimeout(function(){return display.input.focus()},20)}function rangeForUnit(cm,pos,unit){if("char"==unit)return new Range(pos,pos);if("word"==unit)return cm.findWordAt(pos);if("line"==unit)return new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0)));var result=unit(cm,pos);return new Range(result.from,result.to)}function leftButtonSelect(cm,event,start,behavior){function extendTo(pos){if(0!=cmp(lastPos,pos))if(lastPos=pos,"rectangle"==behavior.unit){for(var ranges=[],tabSize=cm.options.tabSize,startCol=countColumn(getLine(doc,start.line).text,start.ch,tabSize),posCol=countColumn(getLine(doc,pos.line).text,pos.ch,tabSize),left=Math.min(startCol,posCol),right=Math.max(startCol,posCol),line=Math.min(start.line,pos.line),end=Math.min(cm.lastLine(),Math.max(start.line,pos.line));line<=end;line++){var text=getLine(doc,line).text,leftPos=findColumn(text,left,tabSize);left==right?ranges.push(new Range(Pos(line,leftPos),Pos(line,leftPos))):text.length>leftPos&&ranges.push(new Range(Pos(line,leftPos),Pos(line,findColumn(text,right,tabSize))))}ranges.length||ranges.push(new Range(start,start)),setSelection(doc,normalizeSelection(startSel.ranges.slice(0,ourIndex).concat(ranges),ourIndex),{origin:"*mouse",scroll:!1}),cm.scrollIntoView(pos)}else{var head,oldRange=ourRange,range$$1=rangeForUnit(cm,pos,behavior.unit),anchor=oldRange.anchor;cmp(range$$1.anchor,anchor)>0?(head=range$$1.head,anchor=minPos(oldRange.from(),range$$1.anchor)):(head=range$$1.anchor,anchor=maxPos(oldRange.to(),range$$1.head));var ranges$1=startSel.ranges.slice(0);ranges$1[ourIndex]=new Range(clipPos(doc,anchor),head),setSelection(doc,normalizeSelection(ranges$1,ourIndex),sel_mouse)}}function extend(e){var curCount=++counter,cur=posFromMouse(cm,e,!0,"rectangle"==behavior.unit);if(cur)if(0!=cmp(cur,lastPos)){cm.curOp.focus=activeElt(),extendTo(cur);var visible=visibleLines(display,doc);(cur.line>=visible.to||cur.line<visible.from)&&setTimeout(operation(cm,function(){counter==curCount&&extend(e)}),150)}else{var outside=e.clientY<editorSize.top?-20:e.clientY>editorSize.bottom?20:0;outside&&setTimeout(operation(cm,function(){counter==curCount&&(display.scroller.scrollTop+=outside,extend(e))}),50)}}function done(e){cm.state.selectingText=!1,counter=1/0,e_preventDefault(e),display.input.focus(),off(document,"mousemove",move),off(document,"mouseup",up),doc.history.lastSelOrigin=null}var display=cm.display,doc=cm.doc;e_preventDefault(event);var ourRange,ourIndex,startSel=doc.sel,ranges=startSel.ranges;if(behavior.addNew&&!behavior.extend?(ourIndex=doc.sel.contains(start),ourRange=ourIndex>-1?ranges[ourIndex]:new Range(start,start)):(ourRange=doc.sel.primary(),ourIndex=doc.sel.primIndex),"rectangle"==behavior.unit)behavior.addNew||(ourRange=new Range(start,start)),start=posFromMouse(cm,event,!0,!0),ourIndex=-1;else{var range$$1=rangeForUnit(cm,start,behavior.unit);ourRange=behavior.extend?extendRange(ourRange,range$$1.anchor,range$$1.head,behavior.extend):range$$1}behavior.addNew?-1==ourIndex?(ourIndex=ranges.length,setSelection(doc,normalizeSelection(ranges.concat([ourRange]),ourIndex),{scroll:!1,origin:"*mouse"})):ranges.length>1&&ranges[ourIndex].empty()&&"char"==behavior.unit&&!behavior.extend?(setSelection(doc,normalizeSelection(ranges.slice(0,ourIndex).concat(ranges.slice(ourIndex+1)),0),{scroll:!1,origin:"*mouse"}),startSel=doc.sel):replaceOneSelection(doc,ourIndex,ourRange,sel_mouse):(ourIndex=0,setSelection(doc,new Selection([ourRange],0),sel_mouse),startSel=doc.sel);var lastPos=start,editorSize=display.wrapper.getBoundingClientRect(),counter=0,move=operation(cm,function(e){e_button(e)?extend(e):done(e)}),up=operation(cm,done);cm.state.selectingText=up,on(document,"mousemove",move),on(document,"mouseup",up)}function gutterEvent(cm,e,type,prevent){var mX,mY;try{mX=e.clientX,mY=e.clientY}catch(e){return!1}if(mX>=Math.floor(cm.display.gutters.getBoundingClientRect().right))return!1;prevent&&e_preventDefault(e);var display=cm.display,lineBox=display.lineDiv.getBoundingClientRect();if(mY>lineBox.bottom||!hasHandler(cm,type))return e_defaultPrevented(e);mY-=lineBox.top-display.viewOffset;for(var i=0;i<cm.options.gutters.length;++i){var g=display.gutters.childNodes[i];if(g&&g.getBoundingClientRect().right>=mX)return signal(cm,type,cm,lineAtHeight(cm.doc,mY),cm.options.gutters[i],e),e_defaultPrevented(e)}}function clickInGutter(cm,e){return gutterEvent(cm,e,"gutterClick",!0)}function onContextMenu(cm,e){eventInWidget(cm.display,e)||contextMenuInGutter(cm,e)||signalDOMEvent(cm,e,"contextmenu")||cm.display.input.onContextMenu(e)}function contextMenuInGutter(cm,e){return!!hasHandler(cm,"gutterContextMenu")&&gutterEvent(cm,e,"gutterContextMenu",!1)}function themeChanged(cm){cm.display.wrapper.className=cm.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+cm.options.theme.replace(/(^|\s)\s*/g," cm-s-"),clearCaches(cm)}function guttersChanged(cm){updateGutters(cm),regChange(cm),alignHorizontally(cm)}function dragDropChanged(cm,value,old){if(!value!=!(old&&old!=Init)){var funcs=cm.display.dragFunctions,toggle=value?on:off;toggle(cm.display.scroller,"dragstart",funcs.start),toggle(cm.display.scroller,"dragenter",funcs.enter),toggle(cm.display.scroller,"dragover",funcs.over),toggle(cm.display.scroller,"dragleave",funcs.leave),toggle(cm.display.scroller,"drop",funcs.drop)}}function wrappingChanged(cm){cm.options.lineWrapping?(addClass(cm.display.wrapper,"CodeMirror-wrap"),cm.display.sizer.style.minWidth="",cm.display.sizerWidth=null):(rmClass(cm.display.wrapper,"CodeMirror-wrap"),findMaxLine(cm)),estimateLineHeights(cm),regChange(cm),clearCaches(cm),setTimeout(function(){return updateScrollbars(cm)},100)}function CodeMirror$1(place,options){var this$1=this;if(!(this instanceof CodeMirror$1))return new CodeMirror$1(place,options);this.options=options=options?copyObj(options):{},copyObj(defaults,options,!1),setGuttersForLineNumbers(options);var doc=options.value;"string"==typeof doc&&(doc=new Doc(doc,options.mode,null,options.lineSeparator,options.direction)),this.doc=doc;var input=new CodeMirror$1.inputStyles[options.inputStyle](this),display=this.display=new Display(place,doc,input);display.wrapper.CodeMirror=this,updateGutters(this),themeChanged(this),options.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),initScrollbars(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new Delayed,keySeq:null,specialChars:null},options.autofocus&&!mobile&&display.input.focus(),ie&&ie_version<11&&setTimeout(function(){return this$1.display.input.reset(!0)},20),registerEventHandlers(this),ensureGlobalHandlers(),startOperation(this),this.curOp.forceUpdate=!0,attachDoc(this,doc),options.autofocus&&!mobile||this.hasFocus()?setTimeout(bind(onFocus,this),20):onBlur(this);for(var opt in optionHandlers)optionHandlers.hasOwnProperty(opt)&&optionHandlers[opt](this$1,options[opt],Init);maybeUpdateLineNumberWidth(this),options.finishInit&&options.finishInit(this);for(var i=0;i<initHooks.length;++i)initHooks[i](this$1);endOperation(this),webkit&&options.lineWrapping&&"optimizelegibility"==getComputedStyle(display.lineDiv).textRendering&&(display.lineDiv.style.textRendering="auto")}function registerEventHandlers(cm){function finishTouch(){d.activeTouch&&(touchFinished=setTimeout(function(){return d.activeTouch=null},1e3),(prevTouch=d.activeTouch).end=+new Date)}function isMouseLikeTouchEvent(e){if(1!=e.touches.length)return!1;var touch=e.touches[0];return touch.radiusX<=1&&touch.radiusY<=1}function farAway(touch,other){if(null==other.left)return!0;var dx=other.left-touch.left,dy=other.top-touch.top;return dx*dx+dy*dy>400}var d=cm.display;on(d.scroller,"mousedown",operation(cm,onMouseDown)),ie&&ie_version<11?on(d.scroller,"dblclick",operation(cm,function(e){if(!signalDOMEvent(cm,e)){var pos=posFromMouse(cm,e);if(pos&&!clickInGutter(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e);var word=cm.findWordAt(pos);extendSelection(cm.doc,word.anchor,word.head)}}})):on(d.scroller,"dblclick",function(e){return signalDOMEvent(cm,e)||e_preventDefault(e)}),captureRightClick||on(d.scroller,"contextmenu",function(e){return onContextMenu(cm,e)});var touchFinished,prevTouch={end:0};on(d.scroller,"touchstart",function(e){if(!signalDOMEvent(cm,e)&&!isMouseLikeTouchEvent(e)){d.input.ensurePolled(),clearTimeout(touchFinished);var now=+new Date;d.activeTouch={start:now,moved:!1,prev:now-prevTouch.end<=300?prevTouch:null},1==e.touches.length&&(d.activeTouch.left=e.touches[0].pageX,d.activeTouch.top=e.touches[0].pageY)}}),on(d.scroller,"touchmove",function(){d.activeTouch&&(d.activeTouch.moved=!0)}),on(d.scroller,"touchend",function(e){var touch=d.activeTouch;if(touch&&!eventInWidget(d,e)&&null!=touch.left&&!touch.moved&&new Date-touch.start<300){var range,pos=cm.coordsChar(d.activeTouch,"page");range=!touch.prev||farAway(touch,touch.prev)?new Range(pos,pos):!touch.prev.prev||farAway(touch,touch.prev.prev)?cm.findWordAt(pos):new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0))),cm.setSelection(range.anchor,range.head),cm.focus(),e_preventDefault(e)}finishTouch()}),on(d.scroller,"touchcancel",finishTouch),on(d.scroller,"scroll",function(){d.scroller.clientHeight&&(updateScrollTop(cm,d.scroller.scrollTop),setScrollLeft(cm,d.scroller.scrollLeft,!0),signal(cm,"scroll",cm))}),on(d.scroller,"mousewheel",function(e){return onScrollWheel(cm,e)}),on(d.scroller,"DOMMouseScroll",function(e){return onScrollWheel(cm,e)}),on(d.wrapper,"scroll",function(){return d.wrapper.scrollTop=d.wrapper.scrollLeft=0}),d.dragFunctions={enter:function(e){signalDOMEvent(cm,e)||e_stop(e)},over:function(e){signalDOMEvent(cm,e)||(onDragOver(cm,e),e_stop(e))},start:function(e){return onDragStart(cm,e)},drop:operation(cm,onDrop),leave:function(e){signalDOMEvent(cm,e)||clearDragCursor(cm)}};var inp=d.input.getField();on(inp,"keyup",function(e){return onKeyUp.call(cm,e)}),on(inp,"keydown",operation(cm,onKeyDown)),on(inp,"keypress",operation(cm,onKeyPress)),on(inp,"focus",function(e){return onFocus(cm,e)}),on(inp,"blur",function(e){return onBlur(cm,e)})}function indentLine(cm,n,how,aggressive){var state,doc=cm.doc;null==how&&(how="add"),"smart"==how&&(doc.mode.indent?state=getContextBefore(cm,n).state:how="prev");var tabSize=cm.options.tabSize,line=getLine(doc,n),curSpace=countColumn(line.text,null,tabSize);line.stateAfter&&(line.stateAfter=null);var indentation,curSpaceString=line.text.match(/^\s*/)[0];if(aggressive||/\S/.test(line.text)){if("smart"==how&&((indentation=doc.mode.indent(state,line.text.slice(curSpaceString.length),line.text))==Pass||indentation>150)){if(!aggressive)return;how="prev"}}else indentation=0,how="not";"prev"==how?indentation=n>doc.first?countColumn(getLine(doc,n-1).text,null,tabSize):0:"add"==how?indentation=curSpace+cm.options.indentUnit:"subtract"==how?indentation=curSpace-cm.options.indentUnit:"number"==typeof how&&(indentation=curSpace+how),indentation=Math.max(0,indentation);var indentString="",pos=0;if(cm.options.indentWithTabs)for(var i=Math.floor(indentation/tabSize);i;--i)pos+=tabSize,indentString+="\t";if(pos<indentation&&(indentString+=spaceStr(indentation-pos)),indentString!=curSpaceString)return replaceRange(doc,indentString,Pos(n,0),Pos(n,curSpaceString.length),"+input"),line.stateAfter=null,!0;for(var i$1=0;i$1<doc.sel.ranges.length;i$1++){var range=doc.sel.ranges[i$1];if(range.head.line==n&&range.head.ch<curSpaceString.length){var pos$1=Pos(n,curSpaceString.length);replaceOneSelection(doc,i$1,new Range(pos$1,pos$1));break}}}function setLastCopied(newLastCopied){lastCopied=newLastCopied}function applyTextInput(cm,inserted,deleted,sel,origin){var doc=cm.doc;cm.display.shift=!1,sel||(sel=doc.sel);var paste=cm.state.pasteIncoming||"paste"==origin,textLines=splitLinesAuto(inserted),multiPaste=null;if(paste&&sel.ranges.length>1)if(lastCopied&&lastCopied.text.join("\n")==inserted){if(sel.ranges.length%lastCopied.text.length==0){multiPaste=[];for(var i=0;i<lastCopied.text.length;i++)multiPaste.push(doc.splitLines(lastCopied.text[i]))}}else textLines.length==sel.ranges.length&&cm.options.pasteLinesPerSelection&&(multiPaste=map(textLines,function(l){return[l]}));for(var updateInput,i$1=sel.ranges.length-1;i$1>=0;i$1--){var range$$1=sel.ranges[i$1],from=range$$1.from(),to=range$$1.to();range$$1.empty()&&(deleted&&deleted>0?from=Pos(from.line,from.ch-deleted):cm.state.overwrite&&!paste?to=Pos(to.line,Math.min(getLine(doc,to.line).text.length,to.ch+lst(textLines).length)):lastCopied&&lastCopied.lineWise&&lastCopied.text.join("\n")==inserted&&(from=to=Pos(from.line,0))),updateInput=cm.curOp.updateInput;var changeEvent={from:from,to:to,text:multiPaste?multiPaste[i$1%multiPaste.length]:textLines,origin:origin||(paste?"paste":cm.state.cutIncoming?"cut":"+input")};makeChange(cm.doc,changeEvent),signalLater(cm,"inputRead",cm,changeEvent)}inserted&&!paste&&triggerElectric(cm,inserted),ensureCursorVisible(cm),cm.curOp.updateInput=updateInput,cm.curOp.typing=!0,cm.state.pasteIncoming=cm.state.cutIncoming=!1}function handlePaste(e,cm){var pasted=e.clipboardData&&e.clipboardData.getData("Text");if(pasted)return e.preventDefault(),cm.isReadOnly()||cm.options.disableInput||runInOp(cm,function(){return applyTextInput(cm,pasted,0,null,"paste")}),!0}function triggerElectric(cm,inserted){if(cm.options.electricChars&&cm.options.smartIndent)for(var sel=cm.doc.sel,i=sel.ranges.length-1;i>=0;i--){var range$$1=sel.ranges[i];if(!(range$$1.head.ch>100||i&&sel.ranges[i-1].head.line==range$$1.head.line)){var mode=cm.getModeAt(range$$1.head),indented=!1;if(mode.electricChars){for(var j=0;j<mode.electricChars.length;j++)if(inserted.indexOf(mode.electricChars.charAt(j))>-1){indented=indentLine(cm,range$$1.head.line,"smart");break}}else mode.electricInput&&mode.electricInput.test(getLine(cm.doc,range$$1.head.line).text.slice(0,range$$1.head.ch))&&(indented=indentLine(cm,range$$1.head.line,"smart"));indented&&signalLater(cm,"electricInput",cm,range$$1.head.line)}}}function copyableRanges(cm){for(var text=[],ranges=[],i=0;i<cm.doc.sel.ranges.length;i++){var line=cm.doc.sel.ranges[i].head.line,lineRange={anchor:Pos(line,0),head:Pos(line+1,0)};ranges.push(lineRange),text.push(cm.getRange(lineRange.anchor,lineRange.head))}return{text:text,ranges:ranges}}function disableBrowserMagic(field,spellcheck){field.setAttribute("autocorrect","off"),field.setAttribute("autocapitalize","off"),field.setAttribute("spellcheck",!!spellcheck)}function hiddenTextarea(){var te=elt("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"),div=elt("div",[te],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");return webkit?te.style.width="1000px":te.setAttribute("wrap","off"),ios&&(te.style.border="1px solid black"),disableBrowserMagic(te),div}function findPosH(doc,pos,dir,unit,visually){function findNextLine(){var l=pos.line+dir;return!(l<doc.first||l>=doc.first+doc.size)&&(pos=new Pos(l,pos.ch,pos.sticky),lineObj=getLine(doc,l))}function moveOnce(boundToLine){var next;if(null==(next=visually?moveVisually(doc.cm,lineObj,pos,dir):moveLogically(lineObj,pos,dir))){if(boundToLine||!findNextLine())return!1;pos=endOfLine(visually,doc.cm,lineObj,pos.line,dir)}else pos=next;return!0}var oldPos=pos,origDir=dir,lineObj=getLine(doc,pos.line);if("char"==unit)moveOnce();else if("column"==unit)moveOnce(!0);else if("word"==unit||"group"==unit)for(var sawType=null,group="group"==unit,helper=doc.cm&&doc.cm.getHelper(pos,"wordChars"),first=!0;!(dir<0)||moveOnce(!first);first=!1){var cur=lineObj.text.charAt(pos.ch)||"\n",type=isWordChar(cur,helper)?"w":group&&"\n"==cur?"n":!group||/\s/.test(cur)?null:"p";if(!group||first||type||(type="s"),sawType&&sawType!=type){dir<0&&(dir=1,moveOnce(),pos.sticky="after");break}if(type&&(sawType=type),dir>0&&!moveOnce(!first))break}var result=skipAtomic(doc,pos,oldPos,origDir,!0);return equalCursorPos(oldPos,result)&&(result.hitSide=!0),result}function findPosV(cm,pos,dir,unit){var y,doc=cm.doc,x=pos.left;if("page"==unit){var pageSize=Math.min(cm.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),moveAmount=Math.max(pageSize-.5*textHeight(cm.display),3);y=(dir>0?pos.bottom:pos.top)+dir*moveAmount}else"line"==unit&&(y=dir>0?pos.bottom+3:pos.top-3);for(var target;(target=coordsChar(cm,x,y)).outside;){if(dir<0?y<=0:y>=doc.height){target.hitSide=!0;break}y+=5*dir}return target}function posToDOM(cm,pos){var view=findViewForLine(cm,pos.line);if(!view||view.hidden)return null;var line=getLine(cm.doc,pos.line),info=mapFromLineView(view,line,pos.line),order=getOrder(line,cm.doc.direction),side="left";order&&(side=getBidiPartAt(order,pos.ch)%2?"right":"left");var result=nodeAndOffsetInLineMap(info.map,pos.ch,side);return result.offset="right"==result.collapse?result.end:result.start,result}function isInGutter(node){for(var scan=node;scan;scan=scan.parentNode)if(/CodeMirror-gutter-wrapper/.test(scan.className))return!0;return!1}function badPos(pos,bad){return bad&&(pos.bad=!0),pos}function domTextBetween(cm,from,to,fromLine,toLine){function recognizeMarker(id){return function(marker){return marker.id==id}}function close(){closing&&(text+=lineSep,closing=!1)}function addText(str){str&&(close(),text+=str)}function walk(node){if(1==node.nodeType){var cmText=node.getAttribute("cm-text");if(null!=cmText)return void addText(cmText||node.textContent.replace(/\u200b/g,""));var range$$1,markerID=node.getAttribute("cm-marker");if(markerID){var found=cm.findMarks(Pos(fromLine,0),Pos(toLine+1,0),recognizeMarker(+markerID));return void(found.length&&(range$$1=found[0].find())&&addText(getBetween(cm.doc,range$$1.from,range$$1.to).join(lineSep)))}if("false"==node.getAttribute("contenteditable"))return;var isBlock=/^(pre|div|p)$/i.test(node.nodeName);isBlock&&close();for(var i=0;i<node.childNodes.length;i++)walk(node.childNodes[i]);isBlock&&(closing=!0)}else 3==node.nodeType&&addText(node.nodeValue)}for(var text="",closing=!1,lineSep=cm.doc.lineSeparator();walk(from),from!=to;)from=from.nextSibling;return text}function domToPos(cm,node,offset){var lineNode;if(node==cm.display.lineDiv){if(!(lineNode=cm.display.lineDiv.childNodes[offset]))return badPos(cm.clipPos(Pos(cm.display.viewTo-1)),!0);node=null,offset=0}else for(lineNode=node;;lineNode=lineNode.parentNode){if(!lineNode||lineNode==cm.display.lineDiv)return null;if(lineNode.parentNode&&lineNode.parentNode==cm.display.lineDiv)break}for(var i=0;i<cm.display.view.length;i++){var lineView=cm.display.view[i];if(lineView.node==lineNode)return locateNodeInLineView(lineView,node,offset)}}function locateNodeInLineView(lineView,node,offset){function find(textNode,topNode,offset){for(var i=-1;i<(maps?maps.length:0);i++)for(var map$$1=i<0?measure.map:maps[i],j=0;j<map$$1.length;j+=3){var curNode=map$$1[j+2];if(curNode==textNode||curNode==topNode){var line=lineNo(i<0?lineView.line:lineView.rest[i]),ch=map$$1[j]+offset;return(offset<0||curNode!=textNode)&&(ch=map$$1[j+(offset?1:0)]),Pos(line,ch)}}}var wrapper=lineView.text.firstChild,bad=!1;if(!node||!contains(wrapper,node))return badPos(Pos(lineNo(lineView.line),0),!0);if(node==wrapper&&(bad=!0,node=wrapper.childNodes[offset],offset=0,!node)){var line=lineView.rest?lst(lineView.rest):lineView.line;return badPos(Pos(lineNo(line),line.text.length),bad)}var textNode=3==node.nodeType?node:null,topNode=node;for(textNode||1!=node.childNodes.length||3!=node.firstChild.nodeType||(textNode=node.firstChild,offset&&(offset=textNode.nodeValue.length));topNode.parentNode!=wrapper;)topNode=topNode.parentNode;var measure=lineView.measure,maps=measure.maps,found=find(textNode,topNode,offset);if(found)return badPos(found,bad);for(var after=topNode.nextSibling,dist=textNode?textNode.nodeValue.length-offset:0;after;after=after.nextSibling){if(found=find(after,after.firstChild,0))return badPos(Pos(found.line,found.ch-dist),bad);dist+=after.textContent.length}for(var before=topNode.previousSibling,dist$1=offset;before;before=before.previousSibling){if(found=find(before,before.firstChild,-1))return badPos(Pos(found.line,found.ch+dist$1),bad);dist$1+=before.textContent.length}}var userAgent=navigator.userAgent,platform=navigator.platform,gecko=/gecko\/\d/i.test(userAgent),ie_upto10=/MSIE \d/.test(userAgent),ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent),edge=/Edge\/(\d+)/.exec(userAgent),ie=ie_upto10||ie_11up||edge,ie_version=ie&&(ie_upto10?document.documentMode||6:+(edge||ie_11up)[1]),webkit=!edge&&/WebKit\//.test(userAgent),qtwebkit=webkit&&/Qt\/\d+\.\d+/.test(userAgent),chrome=!edge&&/Chrome\//.test(userAgent),presto=/Opera\//.test(userAgent),safari=/Apple Computer/.test(navigator.vendor),mac_geMountainLion=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent),phantom=/PhantomJS/.test(userAgent),ios=!edge&&/AppleWebKit/.test(userAgent)&&/Mobile\/\w+/.test(userAgent),android=/Android/.test(userAgent),mobile=ios||android||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent),mac=ios||/Mac/.test(platform),chromeOS=/\bCrOS\b/.test(userAgent),windows=/win/i.test(platform),presto_version=presto&&userAgent.match(/Version\/(\d*\.\d*)/);presto_version&&(presto_version=Number(presto_version[1])),presto_version&&presto_version>=15&&(presto=!1,webkit=!0);var range,flipCtrlCmd=mac&&(qtwebkit||presto&&(null==presto_version||presto_version<12.11)),captureRightClick=gecko||ie&&ie_version>=9,rmClass=function(node,cls){var current=node.className,match=classTest(cls).exec(current);if(match){var after=current.slice(match.index+match[0].length);node.className=current.slice(0,match.index)+(after?match[1]+after:"")}};range=document.createRange?function(node,start,end,endNode){var r=document.createRange();return r.setEnd(endNode||node,end),r.setStart(node,start),r}:function(node,start,end){var r=document.body.createTextRange();try{r.moveToElementText(node.parentNode)}catch(e){return r}return r.collapse(!0),r.moveEnd("character",end),r.moveStart("character",start),r};var selectInput=function(node){node.select()};ios?selectInput=function(node){node.selectionStart=0,node.selectionEnd=node.value.length}:ie&&(selectInput=function(node){try{node.select()}catch(_e){}});var Delayed=function(){this.id=null};Delayed.prototype.set=function(ms,f){clearTimeout(this.id),this.id=setTimeout(f,ms)};var zwspSupported,badBidiRects,scrollerGap=30,Pass={toString:function(){return"CodeMirror.Pass"}},sel_dontScroll={scroll:!1},sel_mouse={origin:"*mouse"},sel_move={origin:"+move"},spaceStrs=[""],nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,extendingChars=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/,sawReadOnlySpans=!1,sawCollapsedSpans=!1,bidiOther=null,bidiOrdering=function(){function charType(code){return code<=247?lowTypes.charAt(code):1424<=code&&code<=1524?"R":1536<=code&&code<=1785?arabicTypes.charAt(code-1536):1774<=code&&code<=2220?"r":8192<=code&&code<=8203?"w":8204==code?"b":"L"}function BidiSpan(level,from,to){this.level=level,this.from=from,this.to=to}var lowTypes="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",arabicTypes="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111",bidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,isNeutral=/[stwN]/,isStrong=/[LRr]/,countsAsLeft=/[Lb1n]/,countsAsNum=/[1n]/;return function(str,direction){var outerType="ltr"==direction?"L":"R";if(0==str.length||"ltr"==direction&&!bidiRE.test(str))return!1;for(var len=str.length,types=[],i=0;i<len;++i)types.push(charType(str.charCodeAt(i)));for(var i$1=0,prev=outerType;i$1<len;++i$1){var type=types[i$1];"m"==type?types[i$1]=prev:prev=type}for(var i$2=0,cur=outerType;i$2<len;++i$2){var type$1=types[i$2];"1"==type$1&&"r"==cur?types[i$2]="n":isStrong.test(type$1)&&(cur=type$1,"r"==type$1&&(types[i$2]="R"))}for(var i$3=1,prev$1=types[0];i$3<len-1;++i$3){var type$2=types[i$3];"+"==type$2&&"1"==prev$1&&"1"==types[i$3+1]?types[i$3]="1":","!=type$2||prev$1!=types[i$3+1]||"1"!=prev$1&&"n"!=prev$1||(types[i$3]=prev$1),prev$1=type$2}for(var i$4=0;i$4<len;++i$4){var type$3=types[i$4];if(","==type$3)types[i$4]="N";else if("%"==type$3){var end=void 0;for(end=i$4+1;end<len&&"%"==types[end];++end);for(var replace=i$4&&"!"==types[i$4-1]||end<len&&"1"==types[end]?"1":"N",j=i$4;j<end;++j)types[j]=replace;i$4=end-1}}for(var i$5=0,cur$1=outerType;i$5<len;++i$5){var type$4=types[i$5];"L"==cur$1&&"1"==type$4?types[i$5]="L":isStrong.test(type$4)&&(cur$1=type$4)}for(var i$6=0;i$6<len;++i$6)if(isNeutral.test(types[i$6])){var end$1=void 0;for(end$1=i$6+1;end$1<len&&isNeutral.test(types[end$1]);++end$1);for(var before="L"==(i$6?types[i$6-1]:outerType),replace$1=before==("L"==(end$1<len?types[end$1]:outerType))?before?"L":"R":outerType,j$1=i$6;j$1<end$1;++j$1)types[j$1]=replace$1;i$6=end$1-1}for(var m,order=[],i$7=0;i$7<len;)if(countsAsLeft.test(types[i$7])){var start=i$7;for(++i$7;i$7<len&&countsAsLeft.test(types[i$7]);++i$7);order.push(new BidiSpan(0,start,i$7))}else{var pos=i$7,at=order.length;for(++i$7;i$7<len&&"L"!=types[i$7];++i$7);for(var j$2=pos;j$2<i$7;)if(countsAsNum.test(types[j$2])){pos<j$2&&order.splice(at,0,new BidiSpan(1,pos,j$2));var nstart=j$2;for(++j$2;j$2<i$7&&countsAsNum.test(types[j$2]);++j$2);order.splice(at,0,new BidiSpan(2,nstart,j$2)),pos=j$2}else++j$2;pos<i$7&&order.splice(at,0,new BidiSpan(1,pos,i$7))}return 1==order[0].level&&(m=str.match(/^\s+/))&&(order[0].from=m[0].length,order.unshift(new BidiSpan(0,0,m[0].length))),1==lst(order).level&&(m=str.match(/\s+$/))&&(lst(order).to-=m[0].length,order.push(new BidiSpan(0,len-m[0].length,len))),"rtl"==direction?order.reverse():order}}(),noHandlers=[],on=function(emitter,type,f){if(emitter.addEventListener)emitter.addEventListener(type,f,!1);else if(emitter.attachEvent)emitter.attachEvent("on"+type,f);else{var map$$1=emitter._handlers||(emitter._handlers={});map$$1[type]=(map$$1[type]||noHandlers).concat(f)}},dragAndDrop=function(){if(ie&&ie_version<9)return!1;var div=elt("div");return"draggable"in div||"dragDrop"in div}(),splitLinesAuto=3!="\n\nb".split(/\n/).length?function(string){for(var pos=0,result=[],l=string.length;pos<=l;){var nl=string.indexOf("\n",pos);-1==nl&&(nl=string.length);var line=string.slice(pos,"\r"==string.charAt(nl-1)?nl-1:nl),rt=line.indexOf("\r");-1!=rt?(result.push(line.slice(0,rt)),pos+=rt+1):(result.push(line),pos=nl+1)}return result}:function(string){return string.split(/\r\n?|\n/)},hasSelection=window.getSelection?function(te){try{return te.selectionStart!=te.selectionEnd}catch(e){return!1}}:function(te){var range$$1;try{range$$1=te.ownerDocument.selection.createRange()}catch(e){}return!(!range$$1||range$$1.parentElement()!=te)&&0!=range$$1.compareEndPoints("StartToEnd",range$$1)},hasCopyEvent=function(){var e=elt("div");return"oncopy"in e||(e.setAttribute("oncopy","return;"),"function"==typeof e.oncopy)}(),badZoomedRects=null,modes={},mimeModes={},modeExtensions={},StringStream=function(string,tabSize,lineOracle){this.pos=this.start=0,this.string=string,this.tabSize=tabSize||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=lineOracle};StringStream.prototype.eol=function(){return this.pos>=this.string.length},StringStream.prototype.sol=function(){return this.pos==this.lineStart},StringStream.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},StringStream.prototype.next=function(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)},StringStream.prototype.eat=function(match){var ch=this.string.charAt(this.pos);if("string"==typeof match?ch==match:ch&&(match.test?match.test(ch):match(ch)))return++this.pos,ch},StringStream.prototype.eatWhile=function(match){for(var start=this.pos;this.eat(match););return this.pos>start},StringStream.prototype.eatSpace=function(){for(var this$1=this,start=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this$1.pos;return this.pos>start},StringStream.prototype.skipToEnd=function(){this.pos=this.string.length},StringStream.prototype.skipTo=function(ch){var found=this.string.indexOf(ch,this.pos);if(found>-1)return this.pos=found,!0},StringStream.prototype.backUp=function(n){this.pos-=n},StringStream.prototype.column=function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=countColumn(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},StringStream.prototype.indentation=function(){return countColumn(this.string,null,this.tabSize)-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},StringStream.prototype.match=function(pattern,consume,caseInsensitive){if("string"!=typeof pattern){var match=this.string.slice(this.pos).match(pattern);return match&&match.index>0?null:(match&&!1!==consume&&(this.pos+=match[0].length),match)}var cased=function(str){return caseInsensitive?str.toLowerCase():str};if(cased(this.string.substr(this.pos,pattern.length))==cased(pattern))return!1!==consume&&(this.pos+=pattern.length),!0},StringStream.prototype.current=function(){return this.string.slice(this.start,this.pos)},StringStream.prototype.hideFirstChars=function(n,inner){this.lineStart+=n;try{return inner()}finally{this.lineStart-=n}},StringStream.prototype.lookAhead=function(n){var oracle=this.lineOracle;return oracle&&oracle.lookAhead(n)};var SavedContext=function(state,lookAhead){this.state=state,this.lookAhead=lookAhead},Context=function(doc,state,line,lookAhead){this.state=state,this.doc=doc,this.line=line,this.maxLookAhead=lookAhead||0};Context.prototype.lookAhead=function(n){var line=this.doc.getLine(this.line+n);return null!=line&&n>this.maxLookAhead&&(this.maxLookAhead=n),line},Context.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},Context.fromSaved=function(doc,saved,line){return saved instanceof SavedContext?new Context(doc,copyState(doc.mode,saved.saved),line,saved.lookAhead):new Context(doc,copyState(doc.mode,saved),line)},Context.prototype.save=function(copy){var state=!1!==copy?copyState(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new SavedContext(state,this.maxLookAhead):state};var Token=function(stream,type,state){this.start=stream.start,this.end=stream.pos,this.string=stream.current(),this.type=type||null,this.state=state},Line=function(text,markedSpans,estimateHeight){this.text=text,attachMarkedSpans(this,markedSpans),this.height=estimateHeight?estimateHeight(this):1};Line.prototype.lineNo=function(){return lineNo(this)},eventMixin(Line);var measureText,styleToClassCache={},styleToClassCacheWithMode={},operationGroup=null,orphanDelayedCallbacks=null,nullRect={left:0,right:0,top:0,bottom:0},NativeScrollbars=function(place,scroll,cm){this.cm=cm;var vert=this.vert=elt("div",[elt("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),horiz=this.horiz=elt("div",[elt("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");place(vert),place(horiz),on(vert,"scroll",function(){vert.clientHeight&&scroll(vert.scrollTop,"vertical")}),on(horiz,"scroll",function(){horiz.clientWidth&&scroll(horiz.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,ie&&ie_version<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};NativeScrollbars.prototype.update=function(measure){var needsH=measure.scrollWidth>measure.clientWidth+1,needsV=measure.scrollHeight>measure.clientHeight+1,sWidth=measure.nativeBarWidth;if(needsV){this.vert.style.display="block",this.vert.style.bottom=needsH?sWidth+"px":"0";var totalHeight=measure.viewHeight-(needsH?sWidth:0);this.vert.firstChild.style.height=Math.max(0,measure.scrollHeight-measure.clientHeight+totalHeight)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(needsH){this.horiz.style.display="block",this.horiz.style.right=needsV?sWidth+"px":"0",this.horiz.style.left=measure.barLeft+"px";var totalWidth=measure.viewWidth-measure.barLeft-(needsV?sWidth:0);this.horiz.firstChild.style.width=Math.max(0,measure.scrollWidth-measure.clientWidth+totalWidth)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&measure.clientHeight>0&&(0==sWidth&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:needsV?sWidth:0,bottom:needsH?sWidth:0}},NativeScrollbars.prototype.setScrollLeft=function(pos){this.horiz.scrollLeft!=pos&&(this.horiz.scrollLeft=pos),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},NativeScrollbars.prototype.setScrollTop=function(pos){this.vert.scrollTop!=pos&&(this.vert.scrollTop=pos),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},NativeScrollbars.prototype.zeroWidthHack=function(){var w=mac&&!mac_geMountainLion?"12px":"18px";this.horiz.style.height=this.vert.style.width=w,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new Delayed,this.disableVert=new Delayed},NativeScrollbars.prototype.enableZeroWidthBar=function(bar,delay,type){function maybeDisable(){var box=bar.getBoundingClientRect();("vert"==type?document.elementFromPoint(box.right-1,(box.top+box.bottom)/2):document.elementFromPoint((box.right+box.left)/2,box.bottom-1))!=bar?bar.style.pointerEvents="none":delay.set(1e3,maybeDisable)}bar.style.pointerEvents="auto",delay.set(1e3,maybeDisable)},NativeScrollbars.prototype.clear=function(){var parent=this.horiz.parentNode;parent.removeChild(this.horiz),parent.removeChild(this.vert)};var NullScrollbars=function(){};NullScrollbars.prototype.update=function(){return{bottom:0,right:0}},NullScrollbars.prototype.setScrollLeft=function(){},NullScrollbars.prototype.setScrollTop=function(){},NullScrollbars.prototype.clear=function(){};var scrollbarModel={native:NativeScrollbars,null:NullScrollbars},nextOpId=0,DisplayUpdate=function(cm,viewport,force){var display=cm.display;this.viewport=viewport,this.visible=visibleLines(display,cm.doc,viewport),this.editorIsHidden=!display.wrapper.offsetWidth,this.wrapperHeight=display.wrapper.clientHeight,this.wrapperWidth=display.wrapper.clientWidth,this.oldDisplayWidth=displayWidth(cm),this.force=force,this.dims=getDimensions(cm),this.events=[]};DisplayUpdate.prototype.signal=function(emitter,type){hasHandler(emitter,type)&&this.events.push(arguments)},DisplayUpdate.prototype.finish=function(){for(var this$1=this,i=0;i<this.events.length;i++)signal.apply(null,this$1.events[i])};var wheelSamples=0,wheelPixelsPerUnit=null;ie?wheelPixelsPerUnit=-.53:gecko?wheelPixelsPerUnit=15:chrome?wheelPixelsPerUnit=-.7:safari&&(wheelPixelsPerUnit=-1/3);var Selection=function(ranges,primIndex){this.ranges=ranges,this.primIndex=primIndex};Selection.prototype.primary=function(){return this.ranges[this.primIndex]},Selection.prototype.equals=function(other){var this$1=this;if(other==this)return!0;if(other.primIndex!=this.primIndex||other.ranges.length!=this.ranges.length)return!1;for(var i=0;i<this.ranges.length;i++){var here=this$1.ranges[i],there=other.ranges[i];if(!equalCursorPos(here.anchor,there.anchor)||!equalCursorPos(here.head,there.head))return!1}return!0},Selection.prototype.deepCopy=function(){for(var this$1=this,out=[],i=0;i<this.ranges.length;i++)out[i]=new Range(copyPos(this$1.ranges[i].anchor),copyPos(this$1.ranges[i].head));return new Selection(out,this.primIndex)},Selection.prototype.somethingSelected=function(){for(var this$1=this,i=0;i<this.ranges.length;i++)if(!this$1.ranges[i].empty())return!0;return!1},Selection.prototype.contains=function(pos,end){var this$1=this;end||(end=pos);for(var i=0;i<this.ranges.length;i++){var range=this$1.ranges[i];if(cmp(end,range.from())>=0&&cmp(pos,range.to())<=0)return i}return-1};var Range=function(anchor,head){this.anchor=anchor,this.head=head};Range.prototype.from=function(){return minPos(this.anchor,this.head)},Range.prototype.to=function(){return maxPos(this.anchor,this.head)},Range.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch},LeafChunk.prototype={chunkSize:function(){return this.lines.length},removeInner:function(at,n){for(var this$1=this,i=at,e=at+n;i<e;++i){var line=this$1.lines[i];this$1.height-=line.height,cleanUpLine(line),signalLater(line,"delete")}this.lines.splice(at,n)},collapse:function(lines){lines.push.apply(lines,this.lines)},insertInner:function(at,lines,height){var this$1=this;this.height+=height,this.lines=this.lines.slice(0,at).concat(lines).concat(this.lines.slice(at));for(var i=0;i<lines.length;++i)lines[i].parent=this$1},iterN:function(at,n,op){for(var this$1=this,e=at+n;at<e;++at)if(op(this$1.lines[at]))return!0}},BranchChunk.prototype={chunkSize:function(){return this.size},removeInner:function(at,n){var this$1=this;this.size-=n;for(var i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize();if(at<sz){var rm=Math.min(n,sz-at),oldHeight=child.height;if(child.removeInner(at,rm),this$1.height-=oldHeight-child.height,sz==rm&&(this$1.children.splice(i--,1),child.parent=null),0==(n-=rm))break;at=0}else at-=sz}if(this.size-n<25&&(this.children.length>1||!(this.children[0]instanceof LeafChunk))){var lines=[];this.collapse(lines),this.children=[new LeafChunk(lines)],this.children[0].parent=this}},collapse:function(lines){for(var this$1=this,i=0;i<this.children.length;++i)this$1.children[i].collapse(lines)},insertInner:function(at,lines,height){var this$1=this;this.size+=lines.length,this.height+=height;for(var i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize();if(at<=sz){if(child.insertInner(at,lines,height),child.lines&&child.lines.length>50){for(var remaining=child.lines.length%25+25,pos=remaining;pos<child.lines.length;){var leaf=new LeafChunk(child.lines.slice(pos,pos+=25));child.height-=leaf.height,this$1.children.splice(++i,0,leaf),leaf.parent=this$1}child.lines=child.lines.slice(0,remaining),this$1.maybeSpill()}break}at-=sz}},maybeSpill:function(){if(!(this.children.length<=10)){var me=this;do{var sibling=new BranchChunk(me.children.splice(me.children.length-5,5));if(me.parent){me.size-=sibling.size,me.height-=sibling.height;var myIndex=indexOf(me.parent.children,me);me.parent.children.splice(myIndex+1,0,sibling)}else{var copy=new BranchChunk(me.children);copy.parent=me,me.children=[copy,sibling],me=copy}sibling.parent=me.parent}while(me.children.length>10);me.parent.maybeSpill()}},iterN:function(at,n,op){for(var this$1=this,i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize();if(at<sz){var used=Math.min(n,sz-at);if(child.iterN(at,used,op))return!0;if(0==(n-=used))break;at=0}else at-=sz}}};var LineWidget=function(doc,node,options){var this$1=this;if(options)for(var opt in options)options.hasOwnProperty(opt)&&(this$1[opt]=options[opt]);this.doc=doc,this.node=node};LineWidget.prototype.clear=function(){var this$1=this,cm=this.doc.cm,ws=this.line.widgets,line=this.line,no=lineNo(line);if(null!=no&&ws){for(var i=0;i<ws.length;++i)ws[i]==this$1&&ws.splice(i--,1);ws.length||(line.widgets=null);var height=widgetHeight(this);updateLineHeight(line,Math.max(0,line.height-height)),cm&&(runInOp(cm,function(){adjustScrollWhenAboveVisible(cm,line,-height),regLineChange(cm,no,"widget")}),signalLater(cm,"lineWidgetCleared",cm,this,no))}},LineWidget.prototype.changed=function(){var this$1=this,oldH=this.height,cm=this.doc.cm,line=this.line;this.height=null;var diff=widgetHeight(this)-oldH;diff&&(updateLineHeight(line,line.height+diff),cm&&runInOp(cm,function(){cm.curOp.forceUpdate=!0,adjustScrollWhenAboveVisible(cm,line,diff),signalLater(cm,"lineWidgetChanged",cm,this$1,lineNo(line))}))},eventMixin(LineWidget);var nextMarkerId=0,TextMarker=function(doc,type){this.lines=[],this.type=type,this.doc=doc,this.id=++nextMarkerId};TextMarker.prototype.clear=function(){var this$1=this;if(!this.explicitlyCleared){var cm=this.doc.cm,withOp=cm&&!cm.curOp;if(withOp&&startOperation(cm),hasHandler(this,"clear")){var found=this.find();found&&signalLater(this,"clear",found.from,found.to)}for(var min=null,max=null,i=0;i<this.lines.length;++i){var line=this$1.lines[i],span=getMarkedSpanFor(line.markedSpans,this$1);cm&&!this$1.collapsed?regLineChange(cm,lineNo(line),"text"):cm&&(null!=span.to&&(max=lineNo(line)),null!=span.from&&(min=lineNo(line))),line.markedSpans=removeMarkedSpan(line.markedSpans,span),null==span.from&&this$1.collapsed&&!lineIsHidden(this$1.doc,line)&&cm&&updateLineHeight(line,textHeight(cm.display))}if(cm&&this.collapsed&&!cm.options.lineWrapping)for(var i$1=0;i$1<this.lines.length;++i$1){var visual=visualLine(this$1.lines[i$1]),len=lineLength(visual);len>cm.display.maxLineLength&&(cm.display.maxLine=visual,cm.display.maxLineLength=len,cm.display.maxLineChanged=!0)}null!=min&&cm&&this.collapsed&®Change(cm,min,max+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,cm&&reCheckSelection(cm.doc)),cm&&signalLater(cm,"markerCleared",cm,this,min,max),withOp&&endOperation(cm),this.parent&&this.parent.clear()}},TextMarker.prototype.find=function(side,lineObj){var this$1=this;null==side&&"bookmark"==this.type&&(side=1);for(var from,to,i=0;i<this.lines.length;++i){var line=this$1.lines[i],span=getMarkedSpanFor(line.markedSpans,this$1);if(null!=span.from&&(from=Pos(lineObj?line:lineNo(line),span.from),-1==side))return from;if(null!=span.to&&(to=Pos(lineObj?line:lineNo(line),span.to),1==side))return to}return from&&{from:from,to:to}},TextMarker.prototype.changed=function(){var this$1=this,pos=this.find(-1,!0),widget=this,cm=this.doc.cm;pos&&cm&&runInOp(cm,function(){var line=pos.line,lineN=lineNo(pos.line),view=findViewForLine(cm,lineN);if(view&&(clearLineMeasurementCacheFor(view),cm.curOp.selectionChanged=cm.curOp.forceUpdate=!0),cm.curOp.updateMaxLine=!0,!lineIsHidden(widget.doc,line)&&null!=widget.height){var oldHeight=widget.height;widget.height=null;var dHeight=widgetHeight(widget)-oldHeight;dHeight&&updateLineHeight(line,line.height+dHeight)}signalLater(cm,"markerChanged",cm,this$1)})},TextMarker.prototype.attachLine=function(line){if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;op.maybeHiddenMarkers&&-1!=indexOf(op.maybeHiddenMarkers,this)||(op.maybeUnhiddenMarkers||(op.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(line)},TextMarker.prototype.detachLine=function(line){if(this.lines.splice(indexOf(this.lines,line),1),!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;(op.maybeHiddenMarkers||(op.maybeHiddenMarkers=[])).push(this)}},eventMixin(TextMarker);var SharedTextMarker=function(markers,primary){var this$1=this;this.markers=markers,this.primary=primary;for(var i=0;i<markers.length;++i)markers[i].parent=this$1};SharedTextMarker.prototype.clear=function(){var this$1=this;if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var i=0;i<this.markers.length;++i)this$1.markers[i].clear();signalLater(this,"clear")}},SharedTextMarker.prototype.find=function(side,lineObj){return this.primary.find(side,lineObj)},eventMixin(SharedTextMarker);var nextDocId=0,Doc=function(text,mode,firstLine,lineSep,direction){if(!(this instanceof Doc))return new Doc(text,mode,firstLine,lineSep,direction);null==firstLine&&(firstLine=0),BranchChunk.call(this,[new LeafChunk([new Line("",null)])]),this.first=firstLine,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.modeFrontier=this.highlightFrontier=firstLine;var start=Pos(firstLine,0);this.sel=simpleSelection(start),this.history=new History(null),this.id=++nextDocId,this.modeOption=mode,this.lineSep=lineSep,this.direction="rtl"==direction?"rtl":"ltr",this.extend=!1,"string"==typeof text&&(text=this.splitLines(text)),updateDoc(this,{from:start,to:start,text:text}),setSelection(this,simpleSelection(start),sel_dontScroll)};Doc.prototype=createObj(BranchChunk.prototype,{constructor:Doc,iter:function(from,to,op){op?this.iterN(from-this.first,to-from,op):this.iterN(this.first,this.first+this.size,from)},insert:function(at,lines){for(var height=0,i=0;i<lines.length;++i)height+=lines[i].height;this.insertInner(at-this.first,lines,height)},remove:function(at,n){this.removeInner(at-this.first,n)},getValue:function(lineSep){var lines=getLines(this,this.first,this.first+this.size);return!1===lineSep?lines:lines.join(lineSep||this.lineSeparator())},setValue:docMethodOp(function(code){var top=Pos(this.first,0),last=this.first+this.size-1;makeChange(this,{from:top,to:Pos(last,getLine(this,last).text.length),text:this.splitLines(code),origin:"setValue",full:!0},!0),this.cm&&scrollToCoords(this.cm,0,0),setSelection(this,simpleSelection(top),sel_dontScroll)}),replaceRange:function(code,from,to,origin){replaceRange(this,code,from=clipPos(this,from),to=to?clipPos(this,to):from,origin)},getRange:function(from,to,lineSep){var lines=getBetween(this,clipPos(this,from),clipPos(this,to));return!1===lineSep?lines:lines.join(lineSep||this.lineSeparator())},getLine:function(line){var l=this.getLineHandle(line);return l&&l.text},getLineHandle:function(line){if(isLine(this,line))return getLine(this,line)},getLineNumber:function(line){return lineNo(line)},getLineHandleVisualStart:function(line){return"number"==typeof line&&(line=getLine(this,line)),visualLine(line)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(pos){return clipPos(this,pos)},getCursor:function(start){var range$$1=this.sel.primary();return null==start||"head"==start?range$$1.head:"anchor"==start?range$$1.anchor:"end"==start||"to"==start||!1===start?range$$1.to():range$$1.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:docMethodOp(function(line,ch,options){setSimpleSelection(this,clipPos(this,"number"==typeof line?Pos(line,ch||0):line),null,options)}),setSelection:docMethodOp(function(anchor,head,options){setSimpleSelection(this,clipPos(this,anchor),clipPos(this,head||anchor),options)}),extendSelection:docMethodOp(function(head,other,options){extendSelection(this,clipPos(this,head),other&&clipPos(this,other),options)}),extendSelections:docMethodOp(function(heads,options){extendSelections(this,clipPosArray(this,heads),options)}),extendSelectionsBy:docMethodOp(function(f,options){extendSelections(this,clipPosArray(this,map(this.sel.ranges,f)),options)}),setSelections:docMethodOp(function(ranges,primary,options){var this$1=this;if(ranges.length){for(var out=[],i=0;i<ranges.length;i++)out[i]=new Range(clipPos(this$1,ranges[i].anchor),clipPos(this$1,ranges[i].head));null==primary&&(primary=Math.min(ranges.length-1,this.sel.primIndex)),setSelection(this,normalizeSelection(out,primary),options)}}),addSelection:docMethodOp(function(anchor,head,options){var ranges=this.sel.ranges.slice(0);ranges.push(new Range(clipPos(this,anchor),clipPos(this,head||anchor))),setSelection(this,normalizeSelection(ranges,ranges.length-1),options)}),getSelection:function(lineSep){for(var lines,this$1=this,ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this$1,ranges[i].from(),ranges[i].to());lines=lines?lines.concat(sel):sel}return!1===lineSep?lines:lines.join(lineSep||this.lineSeparator())},getSelections:function(lineSep){for(var this$1=this,parts=[],ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this$1,ranges[i].from(),ranges[i].to());!1!==lineSep&&(sel=sel.join(lineSep||this$1.lineSeparator())),parts[i]=sel}return parts},replaceSelection:function(code,collapse,origin){for(var dup=[],i=0;i<this.sel.ranges.length;i++)dup[i]=code;this.replaceSelections(dup,collapse,origin||"+input")},replaceSelections:docMethodOp(function(code,collapse,origin){for(var this$1=this,changes=[],sel=this.sel,i=0;i<sel.ranges.length;i++){var range$$1=sel.ranges[i];changes[i]={from:range$$1.from(),to:range$$1.to(),text:this$1.splitLines(code[i]),origin:origin}}for(var newSel=collapse&&"end"!=collapse&&computeReplacedSel(this,changes,collapse),i$1=changes.length-1;i$1>=0;i$1--)makeChange(this$1,changes[i$1]);newSel?setSelectionReplaceHistory(this,newSel):this.cm&&ensureCursorVisible(this.cm)}),undo:docMethodOp(function(){makeChangeFromHistory(this,"undo")}),redo:docMethodOp(function(){makeChangeFromHistory(this,"redo")}),undoSelection:docMethodOp(function(){makeChangeFromHistory(this,"undo",!0)}),redoSelection:docMethodOp(function(){makeChangeFromHistory(this,"redo",!0)}),setExtending:function(val){this.extend=val},getExtending:function(){return this.extend},historySize:function(){for(var hist=this.history,done=0,undone=0,i=0;i<hist.done.length;i++)hist.done[i].ranges||++done;for(var i$1=0;i$1<hist.undone.length;i$1++)hist.undone[i$1].ranges||++undone;return{undo:done,redo:undone}},clearHistory:function(){this.history=new History(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(forceSplit){return forceSplit&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(gen){return this.history.generation==(gen||this.cleanGeneration)},getHistory:function(){return{done:copyHistoryArray(this.history.done),undone:copyHistoryArray(this.history.undone)}},setHistory:function(histData){var hist=this.history=new History(this.history.maxGeneration);hist.done=copyHistoryArray(histData.done.slice(0),null,!0),hist.undone=copyHistoryArray(histData.undone.slice(0),null,!0)},setGutterMarker:docMethodOp(function(line,gutterID,value){return changeLine(this,line,"gutter",function(line){var markers=line.gutterMarkers||(line.gutterMarkers={});return markers[gutterID]=value,!value&&isEmpty(markers)&&(line.gutterMarkers=null),!0})}),clearGutter:docMethodOp(function(gutterID){var this$1=this;this.iter(function(line){line.gutterMarkers&&line.gutterMarkers[gutterID]&&changeLine(this$1,line,"gutter",function(){return line.gutterMarkers[gutterID]=null,isEmpty(line.gutterMarkers)&&(line.gutterMarkers=null),!0})})}),lineInfo:function(line){var n;if("number"==typeof line){if(!isLine(this,line))return null;if(n=line,!(line=getLine(this,line)))return null}else if(null==(n=lineNo(line)))return null;return{line:n,handle:line,text:line.text,gutterMarkers:line.gutterMarkers,textClass:line.textClass,bgClass:line.bgClass,wrapClass:line.wrapClass,widgets:line.widgets}},addLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass";if(line[prop]){if(classTest(cls).test(line[prop]))return!1;line[prop]+=" "+cls}else line[prop]=cls;return!0})}),removeLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass",cur=line[prop];if(!cur)return!1;if(null==cls)line[prop]=null;else{var found=cur.match(classTest(cls));if(!found)return!1;var end=found.index+found[0].length;line[prop]=cur.slice(0,found.index)+(found.index&&end!=cur.length?" ":"")+cur.slice(end)||null}return!0})}),addLineWidget:docMethodOp(function(handle,node,options){return addLineWidget(this,handle,node,options)}),removeLineWidget:function(widget){widget.clear()},markText:function(from,to,options){return markText(this,clipPos(this,from),clipPos(this,to),options,options&&options.type||"range")},setBookmark:function(pos,options){var realOpts={replacedWith:options&&(null==options.nodeType?options.widget:options),insertLeft:options&&options.insertLeft,clearWhenEmpty:!1,shared:options&&options.shared,handleMouseEvents:options&&options.handleMouseEvents};return pos=clipPos(this,pos),markText(this,pos,pos,realOpts,"bookmark")},findMarksAt:function(pos){var markers=[],spans=getLine(this,(pos=clipPos(this,pos)).line).markedSpans;if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];(null==span.from||span.from<=pos.ch)&&(null==span.to||span.to>=pos.ch)&&markers.push(span.marker.parent||span.marker)}return markers},findMarks:function(from,to,filter){from=clipPos(this,from),to=clipPos(this,to);var found=[],lineNo$$1=from.line;return this.iter(from.line,to.line+1,function(line){var spans=line.markedSpans;if(spans)for(var i=0;i<spans.length;i++){var span=spans[i];null!=span.to&&lineNo$$1==from.line&&from.ch>=span.to||null==span.from&&lineNo$$1!=from.line||null!=span.from&&lineNo$$1==to.line&&span.from>=to.ch||filter&&!filter(span.marker)||found.push(span.marker.parent||span.marker)}++lineNo$$1}),found},getAllMarks:function(){var markers=[];return this.iter(function(line){var sps=line.markedSpans;if(sps)for(var i=0;i<sps.length;++i)null!=sps[i].from&&markers.push(sps[i].marker)}),markers},posFromIndex:function(off){var ch,lineNo$$1=this.first,sepSize=this.lineSeparator().length;return this.iter(function(line){var sz=line.text.length+sepSize;if(sz>off)return ch=off,!0;off-=sz,++lineNo$$1}),clipPos(this,Pos(lineNo$$1,ch))},indexFromPos:function(coords){var index=(coords=clipPos(this,coords)).ch;if(coords.line<this.first||coords.ch<0)return 0;var sepSize=this.lineSeparator().length;return this.iter(this.first,coords.line,function(line){index+=line.text.length+sepSize}),index},copy:function(copyHistory){var doc=new Doc(getLines(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);return doc.scrollTop=this.scrollTop,doc.scrollLeft=this.scrollLeft,doc.sel=this.sel,doc.extend=!1,copyHistory&&(doc.history.undoDepth=this.history.undoDepth,doc.setHistory(this.getHistory())),doc},linkedDoc:function(options){options||(options={});var from=this.first,to=this.first+this.size;null!=options.from&&options.from>from&&(from=options.from),null!=options.to&&options.to<to&&(to=options.to);var copy=new Doc(getLines(this,from,to),options.mode||this.modeOption,from,this.lineSep,this.direction);return options.sharedHist&&(copy.history=this.history),(this.linked||(this.linked=[])).push({doc:copy,sharedHist:options.sharedHist}),copy.linked=[{doc:this,isParent:!0,sharedHist:options.sharedHist}],copySharedMarkers(copy,findSharedMarkers(this)),copy},unlinkDoc:function(other){var this$1=this;if(other instanceof CodeMirror$1&&(other=other.doc),this.linked)for(var i=0;i<this.linked.length;++i)if(this$1.linked[i].doc==other){this$1.linked.splice(i,1),other.unlinkDoc(this$1),detachSharedMarkers(findSharedMarkers(this$1));break}if(other.history==this.history){var splitIds=[other.id];linkedDocs(other,function(doc){return splitIds.push(doc.id)},!0),other.history=new History(null),other.history.done=copyHistoryArray(this.history.done,splitIds),other.history.undone=copyHistoryArray(this.history.undone,splitIds)}},iterLinkedDocs:function(f){linkedDocs(this,f)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(str){return this.lineSep?str.split(this.lineSep):splitLinesAuto(str)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:docMethodOp(function(dir){"rtl"!=dir&&(dir="ltr"),dir!=this.direction&&(this.direction=dir,this.iter(function(line){return line.order=null}),this.cm&&directionChanged(this.cm))})}),Doc.prototype.eachLine=Doc.prototype.iter;for(var lastDrop=0,globalsRegistered=!1,keyNames={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"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",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"},i=0;i<10;i++)keyNames[i+48]=keyNames[i+96]=String(i);for(var i$1=65;i$1<=90;i$1++)keyNames[i$1]=String.fromCharCode(i$1);for(var i$2=1;i$2<=12;i$2++)keyNames[i$2+111]=keyNames[i$2+63235]="F"+i$2;var keyMap={};keyMap.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},keyMap.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},keyMap.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},keyMap.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},keyMap.default=mac?keyMap.macDefault:keyMap.pcDefault;var commands={selectAll:selectAll,singleSelection:function(cm){return cm.setSelection(cm.getCursor("anchor"),cm.getCursor("head"),sel_dontScroll)},killLine:function(cm){return deleteNearSelection(cm,function(range){if(range.empty()){var len=getLine(cm.doc,range.head.line).text.length;return range.head.ch==len&&range.head.line<cm.lastLine()?{from:range.head,to:Pos(range.head.line+1,0)}:{from:range.head,to:Pos(range.head.line,len)}}return{from:range.from(),to:range.to()}})},deleteLine:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:clipPos(cm.doc,Pos(range.to().line+1,0))}})},delLineLeft:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:range.from()}})},delWrappedLineLeft:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5;return{from:cm.coordsChar({left:0,top:top},"div"),to:range.from()}})},delWrappedLineRight:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5,rightPos=cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div");return{from:range.from(),to:rightPos}})},undo:function(cm){return cm.undo()},redo:function(cm){return cm.redo()},undoSelection:function(cm){return cm.undoSelection()},redoSelection:function(cm){return cm.redoSelection()},goDocStart:function(cm){return cm.extendSelection(Pos(cm.firstLine(),0))},goDocEnd:function(cm){return cm.extendSelection(Pos(cm.lastLine()))},goLineStart:function(cm){return cm.extendSelectionsBy(function(range){return lineStart(cm,range.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(cm){return cm.extendSelectionsBy(function(range){return lineStartSmart(cm,range.head)},{origin:"+move",bias:1})},goLineEnd:function(cm){return cm.extendSelectionsBy(function(range){return lineEnd(cm,range.head.line)},{origin:"+move",bias:-1})},goLineRight:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5;return cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div")},sel_move)},goLineLeft:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5;return cm.coordsChar({left:0,top:top},"div")},sel_move)},goLineLeftSmart:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5,pos=cm.coordsChar({left:0,top:top},"div");return pos.ch<cm.getLine(pos.line).search(/\S/)?lineStartSmart(cm,range.head):pos},sel_move)},goLineUp:function(cm){return cm.moveV(-1,"line")},goLineDown:function(cm){return cm.moveV(1,"line")},goPageUp:function(cm){return cm.moveV(-1,"page")},goPageDown:function(cm){return cm.moveV(1,"page")},goCharLeft:function(cm){return cm.moveH(-1,"char")},goCharRight:function(cm){return cm.moveH(1,"char")},goColumnLeft:function(cm){return cm.moveH(-1,"column")},goColumnRight:function(cm){return cm.moveH(1,"column")},goWordLeft:function(cm){return cm.moveH(-1,"word")},goGroupRight:function(cm){return cm.moveH(1,"group")},goGroupLeft:function(cm){return cm.moveH(-1,"group")},goWordRight:function(cm){return cm.moveH(1,"word")},delCharBefore:function(cm){return cm.deleteH(-1,"char")},delCharAfter:function(cm){return cm.deleteH(1,"char")},delWordBefore:function(cm){return cm.deleteH(-1,"word")},delWordAfter:function(cm){return cm.deleteH(1,"word")},delGroupBefore:function(cm){return cm.deleteH(-1,"group")},delGroupAfter:function(cm){return cm.deleteH(1,"group")},indentAuto:function(cm){return cm.indentSelection("smart")},indentMore:function(cm){return cm.indentSelection("add")},indentLess:function(cm){return cm.indentSelection("subtract")},insertTab:function(cm){return cm.replaceSelection("\t")},insertSoftTab:function(cm){for(var spaces=[],ranges=cm.listSelections(),tabSize=cm.options.tabSize,i=0;i<ranges.length;i++){var pos=ranges[i].from(),col=countColumn(cm.getLine(pos.line),pos.ch,tabSize);spaces.push(spaceStr(tabSize-col%tabSize))}cm.replaceSelections(spaces)},defaultTab:function(cm){cm.somethingSelected()?cm.indentSelection("add"):cm.execCommand("insertTab")},transposeChars:function(cm){return runInOp(cm,function(){for(var ranges=cm.listSelections(),newSel=[],i=0;i<ranges.length;i++)if(ranges[i].empty()){var cur=ranges[i].head,line=getLine(cm.doc,cur.line).text;if(line)if(cur.ch==line.length&&(cur=new Pos(cur.line,cur.ch-1)),cur.ch>0)cur=new Pos(cur.line,cur.ch+1),cm.replaceRange(line.charAt(cur.ch-1)+line.charAt(cur.ch-2),Pos(cur.line,cur.ch-2),cur,"+transpose");else if(cur.line>cm.doc.first){var prev=getLine(cm.doc,cur.line-1).text;prev&&(cur=new Pos(cur.line,1),cm.replaceRange(line.charAt(0)+cm.doc.lineSeparator()+prev.charAt(prev.length-1),Pos(cur.line-1,prev.length-1),cur,"+transpose"))}newSel.push(new Range(cur,cur))}cm.setSelections(newSel)})},newlineAndIndent:function(cm){return runInOp(cm,function(){for(var sels=cm.listSelections(),i=sels.length-1;i>=0;i--)cm.replaceRange(cm.doc.lineSeparator(),sels[i].anchor,sels[i].head,"+input");sels=cm.listSelections();for(var i$1=0;i$1<sels.length;i$1++)cm.indentLine(sels[i$1].from().line,null,!0);ensureCursorVisible(cm)})},openLine:function(cm){return cm.replaceSelection("\n","start")},toggleOverwrite:function(cm){return cm.toggleOverwrite()}},stopSeq=new Delayed,lastStoppedKey=null,PastClick=function(time,pos,button){this.time=time,this.pos=pos,this.button=button};PastClick.prototype.compare=function(time,pos,button){return this.time+400>time&&0==cmp(pos,this.pos)&&button==this.button};var lastClick,lastDoubleClick,Init={toString:function(){return"CodeMirror.Init"}},defaults={},optionHandlers={};CodeMirror$1.defaults=defaults,CodeMirror$1.optionHandlers=optionHandlers;var initHooks=[];CodeMirror$1.defineInitHook=function(f){return initHooks.push(f)};var lastCopied=null,ContentEditableInput=function(cm){this.cm=cm,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new Delayed,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};ContentEditableInput.prototype.init=function(display){function onCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected())setLastCopied({lineWise:!1,text:cm.getSelections()}),"cut"==e.type&&cm.replaceSelection("",null,"cut");else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text}),"cut"==e.type&&cm.operation(function(){cm.setSelections(ranges.ranges,0,sel_dontScroll),cm.replaceSelection("",null,"cut")})}if(e.clipboardData){e.clipboardData.clearData();var content=lastCopied.text.join("\n");if(e.clipboardData.setData("Text",content),e.clipboardData.getData("Text")==content)return void e.preventDefault()}var kludge=hiddenTextarea(),te=kludge.firstChild;cm.display.lineSpace.insertBefore(kludge,cm.display.lineSpace.firstChild),te.value=lastCopied.text.join("\n");var hadFocus=document.activeElement;selectInput(te),setTimeout(function(){cm.display.lineSpace.removeChild(kludge),hadFocus.focus(),hadFocus==div&&input.showPrimarySelection()},50)}}var this$1=this,input=this,cm=input.cm,div=input.div=display.lineDiv;disableBrowserMagic(div,cm.options.spellcheck),on(div,"paste",function(e){signalDOMEvent(cm,e)||handlePaste(e,cm)||ie_version<=11&&setTimeout(operation(cm,function(){return this$1.updateFromDOM()}),20)}),on(div,"compositionstart",function(e){this$1.composing={data:e.data,done:!1}}),on(div,"compositionupdate",function(e){this$1.composing||(this$1.composing={data:e.data,done:!1})}),on(div,"compositionend",function(e){this$1.composing&&(e.data!=this$1.composing.data&&this$1.readFromDOMSoon(),this$1.composing.done=!0)}),on(div,"touchstart",function(){return input.forceCompositionEnd()}),on(div,"input",function(){this$1.composing||this$1.readFromDOMSoon()}),on(div,"copy",onCopyCut),on(div,"cut",onCopyCut)},ContentEditableInput.prototype.prepareSelection=function(){var result=prepareSelection(this.cm,!1);return result.focus=this.cm.state.focused,result},ContentEditableInput.prototype.showSelection=function(info,takeFocus){info&&this.cm.display.view.length&&((info.focus||takeFocus)&&this.showPrimarySelection(),this.showMultipleSelections(info))},ContentEditableInput.prototype.showPrimarySelection=function(){var sel=window.getSelection(),cm=this.cm,prim=cm.doc.sel.primary(),from=prim.from(),to=prim.to();if(cm.display.viewTo==cm.display.viewFrom||from.line>=cm.display.viewTo||to.line<cm.display.viewFrom)sel.removeAllRanges();else{var curAnchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),curFocus=domToPos(cm,sel.focusNode,sel.focusOffset);if(!curAnchor||curAnchor.bad||!curFocus||curFocus.bad||0!=cmp(minPos(curAnchor,curFocus),from)||0!=cmp(maxPos(curAnchor,curFocus),to)){var view=cm.display.view,start=from.line>=cm.display.viewFrom&&posToDOM(cm,from)||{node:view[0].measure.map[2],offset:0},end=to.line<cm.display.viewTo&&posToDOM(cm,to);if(!end){var measure=view[view.length-1].measure,map$$1=measure.maps?measure.maps[measure.maps.length-1]:measure.map;end={node:map$$1[map$$1.length-1],offset:map$$1[map$$1.length-2]-map$$1[map$$1.length-3]}}if(start&&end){var rng,old=sel.rangeCount&&sel.getRangeAt(0);try{rng=range(start.node,start.offset,end.offset,end.node)}catch(e){}rng&&(!gecko&&cm.state.focused?(sel.collapse(start.node,start.offset),rng.collapsed||(sel.removeAllRanges(),sel.addRange(rng))):(sel.removeAllRanges(),sel.addRange(rng)),old&&null==sel.anchorNode?sel.addRange(old):gecko&&this.startGracePeriod()),this.rememberSelection()}else sel.removeAllRanges()}}},ContentEditableInput.prototype.startGracePeriod=function(){var this$1=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout(function(){this$1.gracePeriod=!1,this$1.selectionChanged()&&this$1.cm.operation(function(){return this$1.cm.curOp.selectionChanged=!0})},20)},ContentEditableInput.prototype.showMultipleSelections=function(info){removeChildrenAndAdd(this.cm.display.cursorDiv,info.cursors),removeChildrenAndAdd(this.cm.display.selectionDiv,info.selection)},ContentEditableInput.prototype.rememberSelection=function(){var sel=window.getSelection();this.lastAnchorNode=sel.anchorNode,this.lastAnchorOffset=sel.anchorOffset,this.lastFocusNode=sel.focusNode,this.lastFocusOffset=sel.focusOffset},ContentEditableInput.prototype.selectionInEditor=function(){var sel=window.getSelection();if(!sel.rangeCount)return!1;var node=sel.getRangeAt(0).commonAncestorContainer;return contains(this.div,node)},ContentEditableInput.prototype.focus=function(){"nocursor"!=this.cm.options.readOnly&&(this.selectionInEditor()||this.showSelection(this.prepareSelection(),!0),this.div.focus())},ContentEditableInput.prototype.blur=function(){this.div.blur()},ContentEditableInput.prototype.getField=function(){return this.div},ContentEditableInput.prototype.supportsTouch=function(){return!0},ContentEditableInput.prototype.receivedFocus=function(){function poll(){input.cm.state.focused&&(input.pollSelection(),input.polling.set(input.cm.options.pollInterval,poll))}var input=this;this.selectionInEditor()?this.pollSelection():runInOp(this.cm,function(){return input.cm.curOp.selectionChanged=!0}),this.polling.set(this.cm.options.pollInterval,poll)},ContentEditableInput.prototype.selectionChanged=function(){var sel=window.getSelection();return sel.anchorNode!=this.lastAnchorNode||sel.anchorOffset!=this.lastAnchorOffset||sel.focusNode!=this.lastFocusNode||sel.focusOffset!=this.lastFocusOffset},ContentEditableInput.prototype.pollSelection=function(){if(null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()){var sel=window.getSelection(),cm=this.cm;if(android&&chrome&&this.cm.options.gutters.length&&isInGutter(sel.anchorNode))return this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),void this.focus();if(!this.composing){this.rememberSelection();var anchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),head=domToPos(cm,sel.focusNode,sel.focusOffset);anchor&&head&&runInOp(cm,function(){setSelection(cm.doc,simpleSelection(anchor,head),sel_dontScroll),(anchor.bad||head.bad)&&(cm.curOp.selectionChanged=!0)})}}},ContentEditableInput.prototype.pollContent=function(){null!=this.readDOMTimeout&&(clearTimeout(this.readDOMTimeout),this.readDOMTimeout=null);var cm=this.cm,display=cm.display,sel=cm.doc.sel.primary(),from=sel.from(),to=sel.to();if(0==from.ch&&from.line>cm.firstLine()&&(from=Pos(from.line-1,getLine(cm.doc,from.line-1).length)),to.ch==getLine(cm.doc,to.line).text.length&&to.line<cm.lastLine()&&(to=Pos(to.line+1,0)),from.line<display.viewFrom||to.line>display.viewTo-1)return!1;var fromIndex,fromLine,fromNode;from.line==display.viewFrom||0==(fromIndex=findViewIndex(cm,from.line))?(fromLine=lineNo(display.view[0].line),fromNode=display.view[0].node):(fromLine=lineNo(display.view[fromIndex].line),fromNode=display.view[fromIndex-1].node.nextSibling);var toLine,toNode,toIndex=findViewIndex(cm,to.line);if(toIndex==display.view.length-1?(toLine=display.viewTo-1,toNode=display.lineDiv.lastChild):(toLine=lineNo(display.view[toIndex+1].line)-1,toNode=display.view[toIndex+1].node.previousSibling),!fromNode)return!1;for(var newText=cm.doc.splitLines(domTextBetween(cm,fromNode,toNode,fromLine,toLine)),oldText=getBetween(cm.doc,Pos(fromLine,0),Pos(toLine,getLine(cm.doc,toLine).text.length));newText.length>1&&oldText.length>1;)if(lst(newText)==lst(oldText))newText.pop(),oldText.pop(),toLine--;else{if(newText[0]!=oldText[0])break;newText.shift(),oldText.shift(),fromLine++}for(var cutFront=0,cutEnd=0,newTop=newText[0],oldTop=oldText[0],maxCutFront=Math.min(newTop.length,oldTop.length);cutFront<maxCutFront&&newTop.charCodeAt(cutFront)==oldTop.charCodeAt(cutFront);)++cutFront;for(var newBot=lst(newText),oldBot=lst(oldText),maxCutEnd=Math.min(newBot.length-(1==newText.length?cutFront:0),oldBot.length-(1==oldText.length?cutFront:0));cutEnd<maxCutEnd&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)++cutEnd;if(1==newText.length&&1==oldText.length&&fromLine==from.line)for(;cutFront&&cutFront>from.ch&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)cutFront--,cutEnd++;newText[newText.length-1]=newBot.slice(0,newBot.length-cutEnd).replace(/^\u200b+/,""),newText[0]=newText[0].slice(cutFront).replace(/\u200b+$/,"");var chFrom=Pos(fromLine,cutFront),chTo=Pos(toLine,oldText.length?lst(oldText).length-cutEnd:0);return newText.length>1||newText[0]||cmp(chFrom,chTo)?(replaceRange(cm.doc,newText,chFrom,chTo,"+input"),!0):void 0},ContentEditableInput.prototype.ensurePolled=function(){this.forceCompositionEnd()},ContentEditableInput.prototype.reset=function(){this.forceCompositionEnd()},ContentEditableInput.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},ContentEditableInput.prototype.readFromDOMSoon=function(){var this$1=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(this$1.readDOMTimeout=null,this$1.composing){if(!this$1.composing.done)return;this$1.composing=null}this$1.updateFromDOM()},80))},ContentEditableInput.prototype.updateFromDOM=function(){var this$1=this;!this.cm.isReadOnly()&&this.pollContent()||runInOp(this.cm,function(){return regChange(this$1.cm)})},ContentEditableInput.prototype.setUneditable=function(node){node.contentEditable="false"},ContentEditableInput.prototype.onKeyPress=function(e){0!=e.charCode&&(e.preventDefault(),this.cm.isReadOnly()||operation(this.cm,applyTextInput)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},ContentEditableInput.prototype.readOnlyChanged=function(val){this.div.contentEditable=String("nocursor"!=val)},ContentEditableInput.prototype.onContextMenu=function(){},ContentEditableInput.prototype.resetPosition=function(){},ContentEditableInput.prototype.needsContentAttribute=!0;var TextareaInput=function(cm){this.cm=cm,this.prevInput="",this.pollingFast=!1,this.polling=new Delayed,this.inaccurateSelection=!1,this.hasSelection=!1,this.composing=null};TextareaInput.prototype.init=function(display){function prepareCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected())setLastCopied({lineWise:!1,text:cm.getSelections()}),input.inaccurateSelection&&(input.prevInput="",input.inaccurateSelection=!1,te.value=lastCopied.text.join("\n"),selectInput(te));else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text}),"cut"==e.type?cm.setSelections(ranges.ranges,null,sel_dontScroll):(input.prevInput="",te.value=ranges.text.join("\n"),selectInput(te))}"cut"==e.type&&(cm.state.cutIncoming=!0)}}var this$1=this,input=this,cm=this.cm,div=this.wrapper=hiddenTextarea(),te=this.textarea=div.firstChild;display.wrapper.insertBefore(div,display.wrapper.firstChild),ios&&(te.style.width="0px"),on(te,"input",function(){ie&&ie_version>=9&&this$1.hasSelection&&(this$1.hasSelection=null),input.poll()}),on(te,"paste",function(e){signalDOMEvent(cm,e)||handlePaste(e,cm)||(cm.state.pasteIncoming=!0,input.fastPoll())}),on(te,"cut",prepareCopyCut),on(te,"copy",prepareCopyCut),on(display.scroller,"paste",function(e){eventInWidget(display,e)||signalDOMEvent(cm,e)||(cm.state.pasteIncoming=!0,input.focus())}),on(display.lineSpace,"selectstart",function(e){eventInWidget(display,e)||e_preventDefault(e)}),on(te,"compositionstart",function(){var start=cm.getCursor("from");input.composing&&input.composing.range.clear(),input.composing={start:start,range:cm.markText(start,cm.getCursor("to"),{className:"CodeMirror-composing"})}}),on(te,"compositionend",function(){input.composing&&(input.poll(),input.composing.range.clear(),input.composing=null)})},TextareaInput.prototype.prepareSelection=function(){var cm=this.cm,display=cm.display,doc=cm.doc,result=prepareSelection(cm);if(cm.options.moveInputWithCursor){var headPos=cursorCoords(cm,doc.sel.primary().head,"div"),wrapOff=display.wrapper.getBoundingClientRect(),lineOff=display.lineDiv.getBoundingClientRect();result.teTop=Math.max(0,Math.min(display.wrapper.clientHeight-10,headPos.top+lineOff.top-wrapOff.top)),result.teLeft=Math.max(0,Math.min(display.wrapper.clientWidth-10,headPos.left+lineOff.left-wrapOff.left))}return result},TextareaInput.prototype.showSelection=function(drawn){var display=this.cm.display;removeChildrenAndAdd(display.cursorDiv,drawn.cursors),removeChildrenAndAdd(display.selectionDiv,drawn.selection),null!=drawn.teTop&&(this.wrapper.style.top=drawn.teTop+"px",this.wrapper.style.left=drawn.teLeft+"px")},TextareaInput.prototype.reset=function(typing){if(!this.contextMenuPending&&!this.composing){var minimal,selected,cm=this.cm,doc=cm.doc;if(cm.somethingSelected()){this.prevInput="";var range$$1=doc.sel.primary(),content=(minimal=hasCopyEvent&&(range$$1.to().line-range$$1.from().line>100||(selected=cm.getSelection()).length>1e3))?"-":selected||cm.getSelection();this.textarea.value=content,cm.state.focused&&selectInput(this.textarea),ie&&ie_version>=9&&(this.hasSelection=content)}else typing||(this.prevInput=this.textarea.value="",ie&&ie_version>=9&&(this.hasSelection=null));this.inaccurateSelection=minimal}},TextareaInput.prototype.getField=function(){return this.textarea},TextareaInput.prototype.supportsTouch=function(){return!1},TextareaInput.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!mobile||activeElt()!=this.textarea))try{this.textarea.focus()}catch(e){}},TextareaInput.prototype.blur=function(){this.textarea.blur()},TextareaInput.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},TextareaInput.prototype.receivedFocus=function(){this.slowPoll()},TextareaInput.prototype.slowPoll=function(){var this$1=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){this$1.poll(),this$1.cm.state.focused&&this$1.slowPoll()})},TextareaInput.prototype.fastPoll=function(){function p(){input.poll()||missed?(input.pollingFast=!1,input.slowPoll()):(missed=!0,input.polling.set(60,p))}var missed=!1,input=this;input.pollingFast=!0,input.polling.set(20,p)},TextareaInput.prototype.poll=function(){var this$1=this,cm=this.cm,input=this.textarea,prevInput=this.prevInput;if(this.contextMenuPending||!cm.state.focused||hasSelection(input)&&!prevInput&&!this.composing||cm.isReadOnly()||cm.options.disableInput||cm.state.keySeq)return!1;var text=input.value;if(text==prevInput&&!cm.somethingSelected())return!1;if(ie&&ie_version>=9&&this.hasSelection===text||mac&&/[\uf700-\uf7ff]/.test(text))return cm.display.input.reset(),!1;if(cm.doc.sel==cm.display.selForContextMenu){var first=text.charCodeAt(0);if(8203!=first||prevInput||(prevInput=""),8666==first)return this.reset(),this.cm.execCommand("undo")}for(var same=0,l=Math.min(prevInput.length,text.length);same<l&&prevInput.charCodeAt(same)==text.charCodeAt(same);)++same;return runInOp(cm,function(){applyTextInput(cm,text.slice(same),prevInput.length-same,null,this$1.composing?"*compose":null),text.length>1e3||text.indexOf("\n")>-1?input.value=this$1.prevInput="":this$1.prevInput=text,this$1.composing&&(this$1.composing.range.clear(),this$1.composing.range=cm.markText(this$1.composing.start,cm.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},TextareaInput.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},TextareaInput.prototype.onKeyPress=function(){ie&&ie_version>=9&&(this.hasSelection=null),this.fastPoll()},TextareaInput.prototype.onContextMenu=function(e){function prepareSelectAllHack(){if(null!=te.selectionStart){var selected=cm.somethingSelected(),extval=""+(selected?te.value:"");te.value="⇚",te.value=extval,input.prevInput=selected?"":"",te.selectionStart=1,te.selectionEnd=extval.length,display.selForContextMenu=cm.doc.sel}}function rehide(){if(input.contextMenuPending=!1,input.wrapper.style.cssText=oldWrapperCSS,te.style.cssText=oldCSS,ie&&ie_version<9&&display.scrollbars.setScrollTop(display.scroller.scrollTop=scrollPos),null!=te.selectionStart){(!ie||ie&&ie_version<9)&&prepareSelectAllHack();var i=0,poll=function(){display.selForContextMenu==cm.doc.sel&&0==te.selectionStart&&te.selectionEnd>0&&""==input.prevInput?operation(cm,selectAll)(cm):i++<10?display.detectingSelectAll=setTimeout(poll,500):(display.selForContextMenu=null,display.input.reset())};display.detectingSelectAll=setTimeout(poll,200)}}var input=this,cm=input.cm,display=cm.display,te=input.textarea,pos=posFromMouse(cm,e),scrollPos=display.scroller.scrollTop;if(pos&&!presto){cm.options.resetSelectionOnContextMenu&&-1==cm.doc.sel.contains(pos)&&operation(cm,setSelection)(cm.doc,simpleSelection(pos),sel_dontScroll);var oldCSS=te.style.cssText,oldWrapperCSS=input.wrapper.style.cssText;input.wrapper.style.cssText="position: absolute";var wrapperBox=input.wrapper.getBoundingClientRect();te.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-wrapperBox.top-5)+"px; left: "+(e.clientX-wrapperBox.left-5)+"px;\n z-index: 1000; background: "+(ie?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";var oldScrollY;if(webkit&&(oldScrollY=window.scrollY),display.input.focus(),webkit&&window.scrollTo(null,oldScrollY),display.input.reset(),cm.somethingSelected()||(te.value=input.prevInput=" "),input.contextMenuPending=!0,display.selForContextMenu=cm.doc.sel,clearTimeout(display.detectingSelectAll),ie&&ie_version>=9&&prepareSelectAllHack(),captureRightClick){e_stop(e);var mouseup=function(){off(window,"mouseup",mouseup),setTimeout(rehide,20)};on(window,"mouseup",mouseup)}else setTimeout(rehide,50)}},TextareaInput.prototype.readOnlyChanged=function(val){val||this.reset(),this.textarea.disabled="nocursor"==val},TextareaInput.prototype.setUneditable=function(){},TextareaInput.prototype.needsContentAttribute=!1,function(CodeMirror){function option(name,deflt,handle,notOnInit){CodeMirror.defaults[name]=deflt,handle&&(optionHandlers[name]=notOnInit?function(cm,val,old){old!=Init&&handle(cm,val,old)}:handle)}var optionHandlers=CodeMirror.optionHandlers;CodeMirror.defineOption=option,CodeMirror.Init=Init,option("value","",function(cm,val){return cm.setValue(val)},!0),option("mode",null,function(cm,val){cm.doc.modeOption=val,loadMode(cm)},!0),option("indentUnit",2,loadMode,!0),option("indentWithTabs",!1),option("smartIndent",!0),option("tabSize",4,function(cm){resetModeState(cm),clearCaches(cm),regChange(cm)},!0),option("lineSeparator",null,function(cm,val){if(cm.doc.lineSep=val,val){var newBreaks=[],lineNo=cm.doc.first;cm.doc.iter(function(line){for(var pos=0;;){var found=line.text.indexOf(val,pos);if(-1==found)break;pos=found+val.length,newBreaks.push(Pos(lineNo,found))}lineNo++});for(var i=newBreaks.length-1;i>=0;i--)replaceRange(cm.doc,val,newBreaks[i],Pos(newBreaks[i].line,newBreaks[i].ch+val.length))}}),option("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,function(cm,val,old){cm.state.specialChars=new RegExp(val.source+(val.test("\t")?"":"|\t"),"g"),old!=Init&&cm.refresh()}),option("specialCharPlaceholder",defaultSpecialCharPlaceholder,function(cm){return cm.refresh()},!0),option("electricChars",!0),option("inputStyle",mobile?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),option("spellcheck",!1,function(cm,val){return cm.getInputField().spellcheck=val},!0),option("rtlMoveVisually",!windows),option("wholeLineUpdateBefore",!0),option("theme","default",function(cm){themeChanged(cm),guttersChanged(cm)},!0),option("keyMap","default",function(cm,val,old){var next=getKeyMap(val),prev=old!=Init&&getKeyMap(old);prev&&prev.detach&&prev.detach(cm,next),next.attach&&next.attach(cm,prev||null)}),option("extraKeys",null),option("configureMouse",null),option("lineWrapping",!1,wrappingChanged,!0),option("gutters",[],function(cm){setGuttersForLineNumbers(cm.options),guttersChanged(cm)},!0),option("fixedGutter",!0,function(cm,val){cm.display.gutters.style.left=val?compensateForHScroll(cm.display)+"px":"0",cm.refresh()},!0),option("coverGutterNextToScrollbar",!1,function(cm){return updateScrollbars(cm)},!0),option("scrollbarStyle","native",function(cm){initScrollbars(cm),updateScrollbars(cm),cm.display.scrollbars.setScrollTop(cm.doc.scrollTop),cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)},!0),option("lineNumbers",!1,function(cm){setGuttersForLineNumbers(cm.options),guttersChanged(cm)},!0),option("firstLineNumber",1,guttersChanged,!0),option("lineNumberFormatter",function(integer){return integer},guttersChanged,!0),option("showCursorWhenSelecting",!1,updateSelection,!0),option("resetSelectionOnContextMenu",!0),option("lineWiseCopyCut",!0),option("pasteLinesPerSelection",!0),option("readOnly",!1,function(cm,val){"nocursor"==val&&(onBlur(cm),cm.display.input.blur()),cm.display.input.readOnlyChanged(val)}),option("disableInput",!1,function(cm,val){val||cm.display.input.reset()},!0),option("dragDrop",!0,dragDropChanged),option("allowDropFileTypes",null),option("cursorBlinkRate",530),option("cursorScrollMargin",0),option("cursorHeight",1,updateSelection,!0),option("singleCursorHeightPerLine",!0,updateSelection,!0),option("workTime",100),option("workDelay",100),option("flattenSpans",!0,resetModeState,!0),option("addModeClass",!1,resetModeState,!0),option("pollInterval",100),option("undoDepth",200,function(cm,val){return cm.doc.history.undoDepth=val}),option("historyEventDelay",1250),option("viewportMargin",10,function(cm){return cm.refresh()},!0),option("maxHighlightLength",1e4,resetModeState,!0),option("moveInputWithCursor",!0,function(cm,val){val||cm.display.input.resetPosition()}),option("tabindex",null,function(cm,val){return cm.display.input.getField().tabIndex=val||""}),option("autofocus",null),option("direction","ltr",function(cm,val){return cm.doc.setDirection(val)},!0)}(CodeMirror$1),function(CodeMirror){var optionHandlers=CodeMirror.optionHandlers,helpers=CodeMirror.helpers={};CodeMirror.prototype={constructor:CodeMirror,focus:function(){window.focus(),this.display.input.focus()},setOption:function(option,value){var options=this.options,old=options[option];options[option]==value&&"mode"!=option||(options[option]=value,optionHandlers.hasOwnProperty(option)&&operation(this,optionHandlers[option])(this,value,old),signal(this,"optionChange",this,option))},getOption:function(option){return this.options[option]},getDoc:function(){return this.doc},addKeyMap:function(map$$1,bottom){this.state.keyMaps[bottom?"push":"unshift"](getKeyMap(map$$1))},removeKeyMap:function(map$$1){for(var maps=this.state.keyMaps,i=0;i<maps.length;++i)if(maps[i]==map$$1||maps[i].name==map$$1)return maps.splice(i,1),!0},addOverlay:methodOp(function(spec,options){var mode=spec.token?spec:CodeMirror.getMode(this.options,spec);if(mode.startState)throw new Error("Overlays may not be stateful.");insertSorted(this.state.overlays,{mode:mode,modeSpec:spec,opaque:options&&options.opaque,priority:options&&options.priority||0},function(overlay){return overlay.priority}),this.state.modeGen++,regChange(this)}),removeOverlay:methodOp(function(spec){for(var this$1=this,overlays=this.state.overlays,i=0;i<overlays.length;++i){var cur=overlays[i].modeSpec;if(cur==spec||"string"==typeof spec&&cur.name==spec)return overlays.splice(i,1),this$1.state.modeGen++,void regChange(this$1)}}),indentLine:methodOp(function(n,dir,aggressive){"string"!=typeof dir&&"number"!=typeof dir&&(dir=null==dir?this.options.smartIndent?"smart":"prev":dir?"add":"subtract"),isLine(this.doc,n)&&indentLine(this,n,dir,aggressive)}),indentSelection:methodOp(function(how){for(var this$1=this,ranges=this.doc.sel.ranges,end=-1,i=0;i<ranges.length;i++){var range$$1=ranges[i];if(range$$1.empty())range$$1.head.line>end&&(indentLine(this$1,range$$1.head.line,how,!0),end=range$$1.head.line,i==this$1.doc.sel.primIndex&&ensureCursorVisible(this$1));else{var from=range$$1.from(),to=range$$1.to(),start=Math.max(end,from.line);end=Math.min(this$1.lastLine(),to.line-(to.ch?0:1))+1;for(var j=start;j<end;++j)indentLine(this$1,j,how);var newRanges=this$1.doc.sel.ranges;0==from.ch&&ranges.length==newRanges.length&&newRanges[i].from().ch>0&&replaceOneSelection(this$1.doc,i,new Range(from,newRanges[i].to()),sel_dontScroll)}}}),getTokenAt:function(pos,precise){return takeToken(this,pos,precise)},getLineTokens:function(line,precise){return takeToken(this,Pos(line),precise,!0)},getTokenTypeAt:function(pos){pos=clipPos(this.doc,pos);var type,styles=getLineStyles(this,getLine(this.doc,pos.line)),before=0,after=(styles.length-1)/2,ch=pos.ch;if(0==ch)type=styles[2];else for(;;){var mid=before+after>>1;if((mid?styles[2*mid-1]:0)>=ch)after=mid;else{if(!(styles[2*mid+1]<ch)){type=styles[2*mid+2];break}before=mid+1}}var cut=type?type.indexOf("overlay "):-1;return cut<0?type:0==cut?null:type.slice(0,cut-1)},getModeAt:function(pos){var mode=this.doc.mode;return mode.innerMode?CodeMirror.innerMode(mode,this.getTokenAt(pos).state).mode:mode},getHelper:function(pos,type){return this.getHelpers(pos,type)[0]},getHelpers:function(pos,type){var this$1=this,found=[];if(!helpers.hasOwnProperty(type))return found;var help=helpers[type],mode=this.getModeAt(pos);if("string"==typeof mode[type])help[mode[type]]&&found.push(help[mode[type]]);else if(mode[type])for(var i=0;i<mode[type].length;i++){var val=help[mode[type][i]];val&&found.push(val)}else mode.helperType&&help[mode.helperType]?found.push(help[mode.helperType]):help[mode.name]&&found.push(help[mode.name]);for(var i$1=0;i$1<help._global.length;i$1++){var cur=help._global[i$1];cur.pred(mode,this$1)&&-1==indexOf(found,cur.val)&&found.push(cur.val)}return found},getStateAfter:function(line,precise){var doc=this.doc;return line=clipLine(doc,null==line?doc.first+doc.size-1:line),getContextBefore(this,line+1,precise).state},cursorCoords:function(start,mode){var pos,range$$1=this.doc.sel.primary();return pos=null==start?range$$1.head:"object"==typeof start?clipPos(this.doc,start):start?range$$1.from():range$$1.to(),cursorCoords(this,pos,mode||"page")},charCoords:function(pos,mode){return charCoords(this,clipPos(this.doc,pos),mode||"page")},coordsChar:function(coords,mode){return coords=fromCoordSystem(this,coords,mode||"page"),coordsChar(this,coords.left,coords.top)},lineAtHeight:function(height,mode){return height=fromCoordSystem(this,{top:height,left:0},mode||"page").top,lineAtHeight(this.doc,height+this.display.viewOffset)},heightAtLine:function(line,mode,includeWidgets){var lineObj,end=!1;if("number"==typeof line){var last=this.doc.first+this.doc.size-1;line<this.doc.first?line=this.doc.first:line>last&&(line=last,end=!0),lineObj=getLine(this.doc,line)}else lineObj=line;return intoCoordSystem(this,lineObj,{top:0,left:0},mode||"page",includeWidgets||end).top+(end?this.doc.height-heightAtLine(lineObj):0)},defaultTextHeight:function(){return textHeight(this.display)},defaultCharWidth:function(){return charWidth(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(pos,node,scroll,vert,horiz){var display=this.display,top=(pos=cursorCoords(this,clipPos(this.doc,pos))).bottom,left=pos.left;if(node.style.position="absolute",node.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(node),display.sizer.appendChild(node),"over"==vert)top=pos.top;else if("above"==vert||"near"==vert){var vspace=Math.max(display.wrapper.clientHeight,this.doc.height),hspace=Math.max(display.sizer.clientWidth,display.lineSpace.clientWidth);("above"==vert||pos.bottom+node.offsetHeight>vspace)&&pos.top>node.offsetHeight?top=pos.top-node.offsetHeight:pos.bottom+node.offsetHeight<=vspace&&(top=pos.bottom),left+node.offsetWidth>hspace&&(left=hspace-node.offsetWidth)}node.style.top=top+"px",node.style.left=node.style.right="","right"==horiz?(left=display.sizer.clientWidth-node.offsetWidth,node.style.right="0px"):("left"==horiz?left=0:"middle"==horiz&&(left=(display.sizer.clientWidth-node.offsetWidth)/2),node.style.left=left+"px"),scroll&&scrollIntoView(this,{left:left,top:top,right:left+node.offsetWidth,bottom:top+node.offsetHeight})},triggerOnKeyDown:methodOp(onKeyDown),triggerOnKeyPress:methodOp(onKeyPress),triggerOnKeyUp:onKeyUp,triggerOnMouseDown:methodOp(onMouseDown),execCommand:function(cmd){if(commands.hasOwnProperty(cmd))return commands[cmd].call(null,this)},triggerElectric:methodOp(function(text){triggerElectric(this,text)}),findPosH:function(from,amount,unit,visually){var this$1=this,dir=1;amount<0&&(dir=-1,amount=-amount);for(var cur=clipPos(this.doc,from),i=0;i<amount&&!(cur=findPosH(this$1.doc,cur,dir,unit,visually)).hitSide;++i);return cur},moveH:methodOp(function(dir,unit){var this$1=this;this.extendSelectionsBy(function(range$$1){return this$1.display.shift||this$1.doc.extend||range$$1.empty()?findPosH(this$1.doc,range$$1.head,dir,unit,this$1.options.rtlMoveVisually):dir<0?range$$1.from():range$$1.to()},sel_move)}),deleteH:methodOp(function(dir,unit){var sel=this.doc.sel,doc=this.doc;sel.somethingSelected()?doc.replaceSelection("",null,"+delete"):deleteNearSelection(this,function(range$$1){var other=findPosH(doc,range$$1.head,dir,unit,!1);return dir<0?{from:other,to:range$$1.head}:{from:range$$1.head,to:other}})}),findPosV:function(from,amount,unit,goalColumn){var this$1=this,dir=1,x=goalColumn;amount<0&&(dir=-1,amount=-amount);for(var cur=clipPos(this.doc,from),i=0;i<amount;++i){var coords=cursorCoords(this$1,cur,"div");if(null==x?x=coords.left:coords.left=x,(cur=findPosV(this$1,coords,dir,unit)).hitSide)break}return cur},moveV:methodOp(function(dir,unit){var this$1=this,doc=this.doc,goals=[],collapse=!this.display.shift&&!doc.extend&&doc.sel.somethingSelected();if(doc.extendSelectionsBy(function(range$$1){if(collapse)return dir<0?range$$1.from():range$$1.to();var headPos=cursorCoords(this$1,range$$1.head,"div");null!=range$$1.goalColumn&&(headPos.left=range$$1.goalColumn),goals.push(headPos.left);var pos=findPosV(this$1,headPos,dir,unit);return"page"==unit&&range$$1==doc.sel.primary()&&addToScrollTop(this$1,charCoords(this$1,pos,"div").top-headPos.top),pos},sel_move),goals.length)for(var i=0;i<doc.sel.ranges.length;i++)doc.sel.ranges[i].goalColumn=goals[i]}),findWordAt:function(pos){var line=getLine(this.doc,pos.line).text,start=pos.ch,end=pos.ch;if(line){var helper=this.getHelper(pos,"wordChars");"before"!=pos.sticky&&end!=line.length||!start?++end:--start;for(var startChar=line.charAt(start),check=isWordChar(startChar,helper)?function(ch){return isWordChar(ch,helper)}:/\s/.test(startChar)?function(ch){return/\s/.test(ch)}:function(ch){return!/\s/.test(ch)&&!isWordChar(ch)};start>0&&check(line.charAt(start-1));)--start;for(;end<line.length&&check(line.charAt(end));)++end}return new Range(Pos(pos.line,start),Pos(pos.line,end))},toggleOverwrite:function(value){null!=value&&value==this.state.overwrite||((this.state.overwrite=!this.state.overwrite)?addClass(this.display.cursorDiv,"CodeMirror-overwrite"):rmClass(this.display.cursorDiv,"CodeMirror-overwrite"),signal(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return this.display.input.getField()==activeElt()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:methodOp(function(x,y){scrollToCoords(this,x,y)}),getScrollInfo:function(){var scroller=this.display.scroller;return{left:scroller.scrollLeft,top:scroller.scrollTop,height:scroller.scrollHeight-scrollGap(this)-this.display.barHeight,width:scroller.scrollWidth-scrollGap(this)-this.display.barWidth,clientHeight:displayHeight(this),clientWidth:displayWidth(this)}},scrollIntoView:methodOp(function(range$$1,margin){null==range$$1?(range$$1={from:this.doc.sel.primary().head,to:null},null==margin&&(margin=this.options.cursorScrollMargin)):"number"==typeof range$$1?range$$1={from:Pos(range$$1,0),to:null}:null==range$$1.from&&(range$$1={from:range$$1,to:null}),range$$1.to||(range$$1.to=range$$1.from),range$$1.margin=margin||0,null!=range$$1.from.line?scrollToRange(this,range$$1):scrollToCoordsRange(this,range$$1.from,range$$1.to,range$$1.margin)}),setSize:methodOp(function(width,height){var this$1=this,interpret=function(val){return"number"==typeof val||/^\d+$/.test(String(val))?val+"px":val};null!=width&&(this.display.wrapper.style.width=interpret(width)),null!=height&&(this.display.wrapper.style.height=interpret(height)),this.options.lineWrapping&&clearLineMeasurementCache(this);var lineNo$$1=this.display.viewFrom;this.doc.iter(lineNo$$1,this.display.viewTo,function(line){if(line.widgets)for(var i=0;i<line.widgets.length;i++)if(line.widgets[i].noHScroll){regLineChange(this$1,lineNo$$1,"widget");break}++lineNo$$1}),this.curOp.forceUpdate=!0,signal(this,"refresh",this)}),operation:function(f){return runInOp(this,f)},refresh:methodOp(function(){var oldHeight=this.display.cachedTextHeight;regChange(this),this.curOp.forceUpdate=!0,clearCaches(this),scrollToCoords(this,this.doc.scrollLeft,this.doc.scrollTop),updateGutterSpace(this),(null==oldHeight||Math.abs(oldHeight-textHeight(this.display))>.5)&&estimateLineHeights(this),signal(this,"refresh",this)}),swapDoc:methodOp(function(doc){var old=this.doc;return old.cm=null,attachDoc(this,doc),clearCaches(this),this.display.input.reset(),scrollToCoords(this,doc.scrollLeft,doc.scrollTop),this.curOp.forceScroll=!0,signalLater(this,"swapDoc",this,old),old}),getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},eventMixin(CodeMirror),CodeMirror.registerHelper=function(type,name,value){helpers.hasOwnProperty(type)||(helpers[type]=CodeMirror[type]={_global:[]}),helpers[type][name]=value},CodeMirror.registerGlobalHelper=function(type,name,predicate,value){CodeMirror.registerHelper(type,name,value),helpers[type]._global.push({pred:predicate,val:value})}}(CodeMirror$1);var dontDelegate="iter insert remove copy getEditor constructor".split(" ");for(var prop in Doc.prototype)Doc.prototype.hasOwnProperty(prop)&&indexOf(dontDelegate,prop)<0&&(CodeMirror$1.prototype[prop]=function(method){return function(){return method.apply(this.doc,arguments)}}(Doc.prototype[prop]));return eventMixin(Doc),CodeMirror$1.inputStyles={textarea:TextareaInput,contenteditable:ContentEditableInput},CodeMirror$1.defineMode=function(name){CodeMirror$1.defaults.mode||"null"==name||(CodeMirror$1.defaults.mode=name),defineMode.apply(this,arguments)},CodeMirror$1.defineMIME=function(mime,spec){mimeModes[mime]=spec},CodeMirror$1.defineMode("null",function(){return{token:function(stream){return stream.skipToEnd()}}}),CodeMirror$1.defineMIME("text/plain","null"),CodeMirror$1.defineExtension=function(name,func){CodeMirror$1.prototype[name]=func},CodeMirror$1.defineDocExtension=function(name,func){Doc.prototype[name]=func},CodeMirror$1.fromTextArea=function(textarea,options){function save(){textarea.value=cm.getValue()}if(options=options?copyObj(options):{},options.value=textarea.value,!options.tabindex&&textarea.tabIndex&&(options.tabindex=textarea.tabIndex),!options.placeholder&&textarea.placeholder&&(options.placeholder=textarea.placeholder),null==options.autofocus){var hasFocus=activeElt();options.autofocus=hasFocus==textarea||null!=textarea.getAttribute("autofocus")&&hasFocus==document.body}var realSubmit;if(textarea.form&&(on(textarea.form,"submit",save),!options.leaveSubmitMethodAlone)){var form=textarea.form;realSubmit=form.submit;try{var wrappedSubmit=form.submit=function(){save(),form.submit=realSubmit,form.submit(),form.submit=wrappedSubmit}}catch(e){}}options.finishInit=function(cm){cm.save=save,cm.getTextArea=function(){return textarea},cm.toTextArea=function(){cm.toTextArea=isNaN,save(),textarea.parentNode.removeChild(cm.getWrapperElement()),textarea.style.display="",textarea.form&&(off(textarea.form,"submit",save),"function"==typeof textarea.form.submit&&(textarea.form.submit=realSubmit))}},textarea.style.display="none";var cm=CodeMirror$1(function(node){return textarea.parentNode.insertBefore(node,textarea.nextSibling)},options);return cm},function(CodeMirror){CodeMirror.off=off,CodeMirror.on=on,CodeMirror.wheelEventPixels=wheelEventPixels,CodeMirror.Doc=Doc,CodeMirror.splitLines=splitLinesAuto,CodeMirror.countColumn=countColumn,CodeMirror.findColumn=findColumn,CodeMirror.isWordChar=isWordCharBasic,CodeMirror.Pass=Pass,CodeMirror.signal=signal,CodeMirror.Line=Line,CodeMirror.changeEnd=changeEnd,CodeMirror.scrollbarModel=scrollbarModel,CodeMirror.Pos=Pos,CodeMirror.cmpPos=cmp,CodeMirror.modes=modes,CodeMirror.mimeModes=mimeModes,CodeMirror.resolveMode=resolveMode,CodeMirror.getMode=getMode,CodeMirror.modeExtensions=modeExtensions,CodeMirror.extendMode=extendMode,CodeMirror.copyState=copyState,CodeMirror.startState=startState,CodeMirror.innerMode=innerMode,CodeMirror.commands=commands,CodeMirror.keyMap=keyMap,CodeMirror.keyName=keyName,CodeMirror.isModifierKey=isModifierKey,CodeMirror.lookupKey=lookupKey,CodeMirror.normalizeKeyMap=normalizeKeyMap,CodeMirror.StringStream=StringStream,CodeMirror.SharedTextMarker=SharedTextMarker,CodeMirror.TextMarker=TextMarker,CodeMirror.LineWidget=LineWidget,CodeMirror.e_preventDefault=e_preventDefault,CodeMirror.e_stopPropagation=e_stopPropagation,CodeMirror.e_stop=e_stop,CodeMirror.addClass=addClass,CodeMirror.contains=contains,CodeMirror.rmClass=rmClass,CodeMirror.keyNames=keyNames}(CodeMirror$1),CodeMirror$1.version="5.27.2",CodeMirror$1})},{}],64:[function(require,module,exports){"use strict";function makeEmptyFunction(arg){return function(){return arg}}var emptyFunction=function(){};emptyFunction.thatReturns=makeEmptyFunction,emptyFunction.thatReturnsFalse=makeEmptyFunction(!1),emptyFunction.thatReturnsTrue=makeEmptyFunction(!0),emptyFunction.thatReturnsNull=makeEmptyFunction(null),emptyFunction.thatReturnsThis=function(){return this},emptyFunction.thatReturnsArgument=function(arg){return arg},module.exports=emptyFunction},{}],65:[function(require,module,exports){(function(process){"use strict";var validateFormat=function(format){};"production"!==process.env.NODE_ENV&&(validateFormat=function(format){if(void 0===format)throw new Error("invariant requires an error message argument")}),module.exports=function(condition,format,a,b,c,d,e,f){if(validateFormat(format),!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;(error=new Error(format.replace(/%s/g,function(){return args[argIndex++]}))).name="Invariant Violation"}throw error.framesToPop=1,error}}}).call(this,require("_process"))},{_process:168}],66:[function(require,module,exports){(function(process){"use strict";var warning=require("./emptyFunction");"production"!==process.env.NODE_ENV&&function(){var printWarning=function(format){for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];var argIndex=0,message="Warning: "+format.replace(/%s/g,function(){return args[argIndex++]});"undefined"!=typeof console&&console.error(message);try{throw new Error(message)}catch(x){}};warning=function(condition,format){if(void 0===format)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(0!==format.indexOf("Failed Composite propType: ")&&!condition){for(var _len2=arguments.length,args=Array(_len2>2?_len2-2:0),_key2=2;_key2<_len2;_key2++)args[_key2-2]=arguments[_key2];printWarning.apply(void 0,[format].concat(args))}}}(),module.exports=warning}).call(this,require("_process"))},{"./emptyFunction":64,_process:168}],67:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLLanguageService=void 0;var _kinds=require("graphql/language/kinds"),_graphql=require("graphql"),_getAutocompleteSuggestions2=require("./getAutocompleteSuggestions"),_getDiagnostics=require("./getDiagnostics"),_getDefinition=require("./getDefinition"),_graphqlLanguageServiceUtils=require("graphql-language-service-utils");exports.GraphQLLanguageService=function(){function GraphQLLanguageService(cache){_classCallCheck(this,GraphQLLanguageService),this._graphQLCache=cache,this._graphQLConfig=cache.getGraphQLConfig()}return GraphQLLanguageService.prototype.getDiagnostics=function(query,uri){var source,appName,schema,customRules,fragmentDefinitions,fragmentDependencies,dependenciesSource,customRulesModulePath,rulesPath;return regeneratorRuntime.async(function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(source=query,appName=this._graphQLConfig.getAppConfigNameByFilePath(uri),schema=void 0,customRules=void 0,!this._graphQLConfig.getSchemaPath(appName)){_context.next=18;break}return _context.next=7,regeneratorRuntime.awrap(this._graphQLCache.getSchema(this._graphQLConfig.getSchemaPath(appName)));case 7:return schema=_context.sent,_context.next=10,regeneratorRuntime.awrap(this._graphQLCache.getFragmentDefinitions(this._graphQLConfig,appName));case 10:return fragmentDefinitions=_context.sent,_context.next=13,regeneratorRuntime.awrap(this._graphQLCache.getFragmentDependencies(query,fragmentDefinitions));case 13:fragmentDependencies=_context.sent,dependenciesSource=fragmentDependencies.reduce(function(prev,cur){return prev+" "+(0,_graphql.print)(cur.definition)},""),source=source+" "+dependenciesSource,(customRulesModulePath=this._graphQLConfig.getCustomValidationRulesModulePath(appName))&&(rulesPath=require.resolve(""+customRulesModulePath))&&(customRules=require(""+rulesPath)(this._graphQLConfig));case 18:return _context.abrupt("return",(0,_getDiagnostics.getDiagnostics)(source,schema,customRules));case 19:case"end":return _context.stop()}},null,this)},GraphQLLanguageService.prototype.getAutocompleteSuggestions=function(query,position,filePath){var appName,schema;return regeneratorRuntime.async(function(_context2){for(;;)switch(_context2.prev=_context2.next){case 0:if(appName=this._graphQLConfig.getAppConfigNameByFilePath(filePath),schema=void 0,!this._graphQLConfig.getSchemaPath(appName)){_context2.next=8;break}return _context2.next=5,regeneratorRuntime.awrap(this._graphQLCache.getSchema(this._graphQLConfig.getSchemaPath(appName)));case 5:if(!(schema=_context2.sent)){_context2.next=8;break}return _context2.abrupt("return",(0,_getAutocompleteSuggestions2.getAutocompleteSuggestions)(schema,query,position));case 8:return _context2.abrupt("return",[]);case 9:case"end":return _context2.stop()}},null,this)},GraphQLLanguageService.prototype.getDefinition=function(query,position,filePath){var appName,ast,node;return regeneratorRuntime.async(function(_context3){for(;;)switch(_context3.prev=_context3.next){case 0:appName=this._graphQLConfig.getAppConfigNameByFilePath(filePath),ast=void 0,_context3.prev=2,ast=(0,_graphql.parse)(query),_context3.next=9;break;case 6:return _context3.prev=6,_context3.t0=_context3.catch(2),_context3.abrupt("return",null);case 9:if(!(node=(0,_graphqlLanguageServiceUtils.getASTNodeAtPosition)(query,ast,position))){_context3.next=16;break}_context3.t1=node.kind,_context3.next=_context3.t1===_kinds.FRAGMENT_SPREAD?14:_context3.t1===_kinds.FRAGMENT_DEFINITION?15:_context3.t1===_kinds.OPERATION_DEFINITION?15:16;break;case 14:return _context3.abrupt("return",this._getDefinitionForFragmentSpread(query,ast,node,filePath,this._graphQLConfig,appName));case 15:return _context3.abrupt("return",(0,_getDefinition.getDefinitionQueryResultForDefinitionNode)(filePath,query,node));case 16:return _context3.abrupt("return",null);case 17:case"end":return _context3.stop()}},null,this,[[2,6]])},GraphQLLanguageService.prototype._getDefinitionForFragmentSpread=function(query,ast,node,filePath,graphQLConfig,appName){var fragmentDefinitions,dependencies,localFragDefinitions,typeCastedDefs,localFragInfos,result;return regeneratorRuntime.async(function(_context4){for(;;)switch(_context4.prev=_context4.next){case 0:return _context4.next=2,regeneratorRuntime.awrap(this._graphQLCache.getFragmentDefinitions(graphQLConfig,appName));case 2:return fragmentDefinitions=_context4.sent,_context4.next=5,regeneratorRuntime.awrap(this._graphQLCache.getFragmentDependenciesForAST(ast,fragmentDefinitions));case 5:return dependencies=_context4.sent,localFragDefinitions=ast.definitions.filter(function(definition){return definition.kind===_kinds.FRAGMENT_DEFINITION}),typeCastedDefs=localFragDefinitions,localFragInfos=typeCastedDefs.map(function(definition){return{filePath:filePath,content:query,definition:definition}}),_context4.next=11,regeneratorRuntime.awrap((0,_getDefinition.getDefinitionQueryResultForFragmentSpread)(query,node,dependencies.concat(localFragInfos)));case 11:return result=_context4.sent,_context4.abrupt("return",result);case 13:case"end":return _context4.stop()}},null,this)},GraphQLLanguageService}()},{"./getAutocompleteSuggestions":69,"./getDefinition":70,"./getDiagnostics":71,graphql:92,"graphql-language-service-utils":81,"graphql/language/kinds":102}],68:[function(require,module,exports){"use strict";function forEachState(stack,fn){for(var reverseStateStack=[],state=stack;state&&state.kind;)reverseStateStack.push(state),state=state.prevState;for(var i=reverseStateStack.length-1;i>=0;i--)fn(reverseStateStack[i])}function filterAndSortList(list,text){return text?filterNonEmpty(filterNonEmpty(list.map(function(entry){return{proximity:getProximity(normalizeText(entry.label),text),entry:entry}}),function(pair){return pair.proximity<=2}),function(pair){return!pair.entry.isDeprecated}).sort(function(a,b){return(a.entry.isDeprecated?1:0)-(b.entry.isDeprecated?1:0)||a.proximity-b.proximity||a.entry.label.length-b.entry.label.length}).map(function(pair){return pair.entry}):filterNonEmpty(list,function(entry){return!entry.isDeprecated})}function filterNonEmpty(array,predicate){var filtered=array.filter(predicate);return 0===filtered.length?array:filtered}function normalizeText(text){return text.toLowerCase().replace(/\W/g,"")}function getProximity(suggestion,text){var proximity=lexicalDistance(text,suggestion);return suggestion.length>text.length&&(proximity-=suggestion.length-text.length-1,proximity+=0===suggestion.indexOf(text)?0:.5),proximity}function lexicalDistance(a,b){var i=void 0,j=void 0,d=[],aLength=a.length,bLength=b.length;for(i=0;i<=aLength;i++)d[i]=[i];for(j=1;j<=bLength;j++)d[0][j]=j;for(i=1;i<=aLength;i++)for(j=1;j<=bLength;j++){var cost=a[i-1]===b[j-1]?0:1;d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+cost),i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1]&&(d[i][j]=Math.min(d[i][j],d[i-2][j-2]+cost))}return d[aLength][bLength]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getDefinitionState=function(tokenState){var definitionState=void 0;return forEachState(tokenState,function(state){switch(state.kind){case"Query":case"ShortQuery":case"Mutation":case"Subscription":case"FragmentDefinition":definitionState=state}}),definitionState},exports.getFieldDef=function(schema,type,fieldName){return fieldName===_introspection.SchemaMetaFieldDef.name&&schema.getQueryType()===type?_introspection.SchemaMetaFieldDef:fieldName===_introspection.TypeMetaFieldDef.name&&schema.getQueryType()===type?_introspection.TypeMetaFieldDef:fieldName===_introspection.TypeNameMetaFieldDef.name&&(0,_graphql.isCompositeType)(type)?_introspection.TypeNameMetaFieldDef:type.getFields&&"function"==typeof type.getFields?type.getFields()[fieldName]:null},exports.forEachState=forEachState,exports.objectValues=function(object){for(var keys=Object.keys(object),len=keys.length,values=new Array(len),i=0;i<len;++i)values[i]=object[keys[i]];return values},exports.hintList=function(token,list){return filterAndSortList(list,normalizeText(token.string))};var _graphql=require("graphql"),_introspection=require("graphql/type/introspection")},{graphql:92,"graphql/type/introspection":115}],69:[function(require,module,exports){"use strict";function getSuggestionsForFieldNames(token,typeInfo,schema){if(typeInfo.parentType){var parentType=typeInfo.parentType,fields=parentType.getFields instanceof Function?(0,_autocompleteUtils.objectValues)(parentType.getFields()):[];return(0,_graphql.isAbstractType)(parentType)&&fields.push(_graphql.TypeNameMetaFieldDef),parentType===schema.getQueryType()&&fields.push(_graphql.SchemaMetaFieldDef,_graphql.TypeMetaFieldDef),(0,_autocompleteUtils.hintList)(token,fields.map(function(field){return{label:field.name,detail:String(field.type),documentation:field.description,isDeprecated:field.isDeprecated,deprecationReason:field.deprecationReason}}))}return[]}function getSuggestionsForInputValues(token,typeInfo){var namedInputType=(0,_graphql.getNamedType)(typeInfo.inputType);if(namedInputType instanceof _graphql.GraphQLEnumType){var values=namedInputType.getValues();return(0,_autocompleteUtils.hintList)(token,values.map(function(value){return{label:value.name,detail:String(namedInputType),documentation:value.description,isDeprecated:value.isDeprecated,deprecationReason:value.deprecationReason}}))}return namedInputType===_graphql.GraphQLBoolean?(0,_autocompleteUtils.hintList)(token,[{label:"true",detail:String(_graphql.GraphQLBoolean),documentation:"Not false."},{label:"false",detail:String(_graphql.GraphQLBoolean),documentation:"Not true."}]):[]}function getSuggestionsForFragmentTypeConditions(token,typeInfo,schema){var possibleTypes=void 0;if(typeInfo.parentType)if((0,_graphql.isAbstractType)(typeInfo.parentType)){var abstractType=(0,_graphql.assertAbstractType)(typeInfo.parentType),possibleObjTypes=schema.getPossibleTypes(abstractType),possibleIfaceMap=Object.create(null);possibleObjTypes.forEach(function(type){type.getInterfaces().forEach(function(iface){possibleIfaceMap[iface.name]=iface})}),possibleTypes=possibleObjTypes.concat((0,_autocompleteUtils.objectValues)(possibleIfaceMap))}else possibleTypes=[typeInfo.parentType];else{var typeMap=schema.getTypeMap();possibleTypes=(0,_autocompleteUtils.objectValues)(typeMap).filter(_graphql.isCompositeType)}return(0,_autocompleteUtils.hintList)(token,possibleTypes.map(function(type){var namedType=(0,_graphql.getNamedType)(type);return{label:String(type),documentation:namedType&&namedType.description||""}}))}function getSuggestionsForFragmentSpread(token,typeInfo,schema,queryText){var typeMap=schema.getTypeMap(),defState=(0,_autocompleteUtils.getDefinitionState)(token.state),relevantFrags=getFragmentDefinitions(queryText).filter(function(frag){return typeMap[frag.typeCondition.name.value]&&!(defState&&"FragmentDefinition"===defState.kind&&defState.name===frag.name.value)&&(0,_graphql.isCompositeType)(typeInfo.parentType)&&(0,_graphql.isCompositeType)(typeMap[frag.typeCondition.name.value])&&(0,_graphql.doTypesOverlap)(schema,typeInfo.parentType,typeMap[frag.typeCondition.name.value])});return(0,_autocompleteUtils.hintList)(token,relevantFrags.map(function(frag){return{label:frag.name.value,detail:String(typeMap[frag.typeCondition.name.value]),documentation:"fragment "+frag.name.value+" on "+frag.typeCondition.name.value}}))}function getFragmentDefinitions(queryText){var fragmentDefs=[];return runOnlineParser(queryText,function(_,state){"FragmentDefinition"===state.kind&&state.name&&state.type&&fragmentDefs.push({kind:"FragmentDefinition",name:{kind:"Name",value:state.name},selectionSet:{kind:"SelectionSet",selections:[]},typeCondition:{kind:"NamedType",name:{kind:"Name",value:state.type}}})}),fragmentDefs}function getSuggestionsForVariableDefinition(token,schema){var inputTypeMap=schema.getTypeMap(),inputTypes=(0,_autocompleteUtils.objectValues)(inputTypeMap).filter(_graphql.isInputType);return(0,_autocompleteUtils.hintList)(token,inputTypes.map(function(type){return{label:type.name,documentation:type.description}}))}function getSuggestionsForDirective(token,state,schema){if(state.prevState&&state.prevState.kind){var directives=schema.getDirectives().filter(function(directive){return canUseDirective(state.prevState,directive)});return(0,_autocompleteUtils.hintList)(token,directives.map(function(directive){return{label:directive.name,documentation:directive.description||""}}))}return[]}function getTokenAtPosition(queryText,cursor){var styleAtCursor=null,stateAtCursor=null,stringAtCursor=null,token=runOnlineParser(queryText,function(stream,state,style,index){if(index===cursor.line&&stream.getCurrentPosition()>=cursor.character)return styleAtCursor=style,stateAtCursor=_extends({},state),stringAtCursor=stream.current(),"BREAK"});return{start:token.start,end:token.end,string:stringAtCursor||token.string,state:stateAtCursor||token.state,style:styleAtCursor||token.style}}function runOnlineParser(queryText,callback){for(var lines=queryText.split("\n"),parser=(0,_graphqlLanguageServiceParser.onlineParser)(),state=parser.startState(),style="",stream=new _graphqlLanguageServiceParser.CharacterStream(""),i=0;i<lines.length;i++){for(stream=new _graphqlLanguageServiceParser.CharacterStream(lines[i]);!stream.eol()&&"BREAK"!==callback(stream,state,style=parser.token(stream,state),i););callback(stream,state,style,i),state.kind||(state=parser.startState())}return{start:stream.getStartOfToken(),end:stream.getCurrentPosition(),string:stream.current(),state:state,style:style}}function canUseDirective(state,directive){if(!state||!state.kind)return!1;var kind=state.kind,locations=directive.locations;switch(kind){case"Query":return-1!==locations.indexOf("QUERY");case"Mutation":return-1!==locations.indexOf("MUTATION");case"Subscription":return-1!==locations.indexOf("SUBSCRIPTION");case"Field":case"AliasedField":return-1!==locations.indexOf("FIELD");case"FragmentDefinition":return-1!==locations.indexOf("FRAGMENT_DEFINITION");case"FragmentSpread":return-1!==locations.indexOf("FRAGMENT_SPREAD");case"InlineFragment":return-1!==locations.indexOf("INLINE_FRAGMENT");case"SchemaDef":return-1!==locations.indexOf("SCHEMA");case"ScalarDef":return-1!==locations.indexOf("SCALAR");case"ObjectTypeDef":return-1!==locations.indexOf("OBJECT");case"FieldDef":return-1!==locations.indexOf("FIELD_DEFINITION");case"InterfaceDef":return-1!==locations.indexOf("INTERFACE");case"UnionDef":return-1!==locations.indexOf("UNION");case"EnumDef":return-1!==locations.indexOf("ENUM");case"EnumValue":return-1!==locations.indexOf("ENUM_VALUE");case"InputDef":return-1!==locations.indexOf("INPUT_OBJECT");case"InputValueDef":switch(state.prevState&&state.prevState.kind){case"ArgumentsDef":return-1!==locations.indexOf("ARGUMENT_DEFINITION");case"InputDef":return-1!==locations.indexOf("INPUT_FIELD_DEFINITION")}}return!1}function getTypeInfo(schema,tokenState){var argDef=void 0,argDefs=void 0,directiveDef=void 0,enumValue=void 0,fieldDef=void 0,inputType=void 0,objectFieldDefs=void 0,parentType=void 0,type=void 0;return(0,_autocompleteUtils.forEachState)(tokenState,function(state){switch(state.kind){case"Query":case"ShortQuery":type=schema.getQueryType();break;case"Mutation":type=schema.getMutationType();break;case"Subscription":type=schema.getSubscriptionType();break;case"InlineFragment":case"FragmentDefinition":state.type&&(type=schema.getType(state.type));break;case"Field":case"AliasedField":type&&state.name?(fieldDef=parentType?(0,_autocompleteUtils.getFieldDef)(schema,parentType,state.name):null,type=fieldDef?fieldDef.type:null):fieldDef=null;break;case"SelectionSet":parentType=(0,_graphql.getNamedType)(type);break;case"Directive":directiveDef=state.name?schema.getDirective(state.name):null;break;case"Arguments":if(state.prevState)switch(state.prevState.kind){case"Field":argDefs=fieldDef&&fieldDef.args;break;case"Directive":argDefs=directiveDef&&directiveDef.args;break;case"AliasedField":var name=state.prevState&&state.prevState.name;if(!name){argDefs=null;break}var field=parentType?(0,_autocompleteUtils.getFieldDef)(schema,parentType,name):null;if(!field){argDefs=null;break}argDefs=field.args;break;default:argDefs=null}else argDefs=null;break;case"Argument":if(argDefs)for(var i=0;i<argDefs.length;i++)if(argDefs[i].name===state.name){argDef=argDefs[i];break}inputType=argDef&&argDef.type;break;case"EnumValue":var enumType=(0,_graphql.getNamedType)(inputType);enumValue=enumType instanceof _graphql.GraphQLEnumType?find(enumType.getValues(),function(val){return val.value===state.name}):null;break;case"ListValue":var nullableType=(0,_graphql.getNullableType)(inputType);inputType=nullableType instanceof _graphql.GraphQLList?nullableType.ofType:null;break;case"ObjectValue":var objectType=(0,_graphql.getNamedType)(inputType);objectFieldDefs=objectType instanceof _graphql.GraphQLInputObjectType?objectType.getFields():null;break;case"ObjectField":var objectField=state.name&&objectFieldDefs?objectFieldDefs[state.name]:null;inputType=objectField&&objectField.type;break;case"NamedType":state.name&&(type=schema.getType(state.name))}}),{argDef:argDef,argDefs:argDefs,directiveDef:directiveDef,enumValue:enumValue,fieldDef:fieldDef,inputType:inputType,objectFieldDefs:objectFieldDefs,parentType:parentType,type:type}}function find(array,predicate){for(var i=0;i<array.length;i++)if(predicate(array[i]))return array[i];return null}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target};exports.getAutocompleteSuggestions=function(schema,queryText,cursor,contextToken){var token=contextToken||getTokenAtPosition(queryText,cursor),state="Invalid"===token.state.kind?token.state.prevState:token.state;if(!state)return[];var kind=state.kind,step=state.step,typeInfo=getTypeInfo(schema,token.state);if("Document"===kind)return(0,_autocompleteUtils.hintList)(token,[{label:"query"},{label:"mutation"},{label:"subscription"},{label:"fragment"},{label:"{"}]);if("SelectionSet"===kind||"Field"===kind||"AliasedField"===kind)return getSuggestionsForFieldNames(token,typeInfo,schema);if("Arguments"===kind||"Argument"===kind&&0===step){var argDefs=typeInfo.argDefs;if(argDefs)return(0,_autocompleteUtils.hintList)(token,argDefs.map(function(argDef){return{label:argDef.name,detail:String(argDef.type),documentation:argDef.description}}))}if(("ObjectValue"===kind||"ObjectField"===kind&&0===step)&&typeInfo.objectFieldDefs){var objectFields=(0,_autocompleteUtils.objectValues)(typeInfo.objectFieldDefs);return(0,_autocompleteUtils.hintList)(token,objectFields.map(function(field){return{label:field.name,detail:String(field.type),documentation:field.description}}))}return"EnumValue"===kind||"ListValue"===kind&&1===step||"ObjectField"===kind&&2===step||"Argument"===kind&&2===step?getSuggestionsForInputValues(token,typeInfo):"TypeCondition"===kind&&1===step||"NamedType"===kind&&null!=state.prevState&&"TypeCondition"===state.prevState.kind?getSuggestionsForFragmentTypeConditions(token,typeInfo,schema):"FragmentSpread"===kind&&1===step?getSuggestionsForFragmentSpread(token,typeInfo,schema,queryText):"VariableDefinition"===kind&&2===step||"ListType"===kind&&1===step||"NamedType"===kind&&state.prevState&&("VariableDefinition"===state.prevState.kind||"ListType"===state.prevState.kind)?getSuggestionsForVariableDefinition(token,schema):"Directive"===kind?getSuggestionsForDirective(token,state,schema):[]};var _graphql=require("graphql"),_graphqlLanguageServiceParser=require("graphql-language-service-parser"),_autocompleteUtils=require("./autocompleteUtils")},{"./autocompleteUtils":68,graphql:92,"graphql-language-service-parser":77}],70:[function(require,module,exports){(function(process){"use strict";function getRange(text,node){var location=node.loc;return(0,_assert2.default)(location,"Expected ASTNode to have a location."),(0,_graphqlLanguageServiceUtils.locToRange)(text,location)}function getPosition(text,node){var location=node.loc;return(0,_assert2.default)(location,"Expected ASTNode to have a location."),(0,_graphqlLanguageServiceUtils.offsetToPosition)(text,location.start)}function getDefinitionForFragmentDefinition(path,text,definition){var name=definition.name;return(0,_assert2.default)(name,"Expected ASTNode to have a Name."),{path:path,position:getPosition(text,name),range:getRange(text,definition),name:name.value||"",language:LANGUAGE,projectRoot:path}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.LANGUAGE=void 0,exports.getDefinitionQueryResultForFragmentSpread=function(text,fragment,dependencies){var name,defNodes,definitions;return regeneratorRuntime.async(function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(name=fragment.name.value,0!==(defNodes=dependencies.filter(function(_ref){return _ref.definition.name.value===name})).length){_context.next=5;break}return process.stderr.write("Definition not found for GraphQL fragment "+name),_context.abrupt("return",{queryRange:[],definitions:[]});case 5:return definitions=defNodes.map(function(_ref2){var filePath=_ref2.filePath,content=_ref2.content,definition=_ref2.definition;return getDefinitionForFragmentDefinition(filePath||"",content,definition)}),_context.abrupt("return",{definitions:definitions,queryRange:definitions.map(function(_){return getRange(text,fragment)})});case 7:case"end":return _context.stop()}},null,this)},exports.getDefinitionQueryResultForDefinitionNode=function(path,text,definition){return{definitions:[getDefinitionForFragmentDefinition(path,text,definition)],queryRange:definition.name?[getRange(text,definition.name)]:[]}};var _graphqlLanguageServiceUtils=require("graphql-language-service-utils"),_assert2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("assert")),LANGUAGE=exports.LANGUAGE="GraphQL"}).call(this,require("_process"))},{_process:168,assert:34,"graphql-language-service-utils":81}],71:[function(require,module,exports){"use strict";function mapCat(array,mapper){return Array.prototype.concat.apply([],array.map(mapper))}function annotations(error,severity,type){return error.nodes?error.nodes.map(function(node){var highlightNode="Variable"!==node.kind&&node.name?node.name:node.variable?node.variable:node;(0,_assert2.default)(error.locations,"GraphQL validation error requires locations.");var loc=error.locations[0],highlightLoc=getLocation(highlightNode),end=loc.column+(highlightLoc.end-highlightLoc.start);return{source:"GraphQL: "+type,message:error.message,severity:severity,range:new _graphqlLanguageServiceUtils.Range(new _graphqlLanguageServiceUtils.Position(loc.line-1,loc.column-1),new _graphqlLanguageServiceUtils.Position(loc.line-1,end))}}):[]}function getLocation(node){var location=node.loc;return(0,_assert2.default)(location,"Expected ASTNode to have a location."),location}function getRange(location,queryText){var parser=(0,_graphqlLanguageServiceParser.onlineParser)(),state=parser.startState(),lines=queryText.split("\n");(0,_assert2.default)(lines.length>=location.line,"Query text must have more lines than where the error happened");for(var stream=null,i=0;i<location.line;i++)for(stream=new _graphqlLanguageServiceParser.CharacterStream(lines[i]);!stream.eol()&&"invalidchar"!==parser.token(stream,state););(0,_assert2.default)(stream,"Expected Parser stream to be available.");var line=location.line-1,start=stream.getStartOfToken(),end=stream.getCurrentPosition();return new _graphqlLanguageServiceUtils.Range(new _graphqlLanguageServiceUtils.Position(line,start),new _graphqlLanguageServiceUtils.Position(line,end))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.SEVERITY=void 0,exports.getDiagnostics=function(queryText){var schema=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,customRules=arguments[2],ast=null;try{ast=(0,_graphql.parse)(queryText)}catch(error){var range=getRange(error.locations[0],queryText);return[{severity:SEVERITY.ERROR,message:error.message,source:"GraphQL: Syntax",range:range}]}if(!schema)return[];var validationErrorAnnotations=mapCat((0,_graphqlLanguageServiceUtils.validateWithCustomRules)(schema,ast,customRules),function(error){return annotations(error,SEVERITY.ERROR,"Validation")}),deprecationWarningAnnotations=_graphql.findDeprecatedUsages?mapCat((0,_graphql.findDeprecatedUsages)(schema,ast),function(error){return annotations(error,SEVERITY.WARNING,"Deprecation")}):[];return validationErrorAnnotations.concat(deprecationWarningAnnotations)};var _assert2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("assert")),_graphql=require("graphql"),_graphqlLanguageServiceParser=require("graphql-language-service-parser"),_graphqlLanguageServiceUtils=require("graphql-language-service-utils"),SEVERITY=exports.SEVERITY={ERROR:1,WARNING:2,INFORMATION:3,HINT:4}},{assert:34,graphql:92,"graphql-language-service-parser":77,"graphql-language-service-utils":81}],72:[function(require,module,exports){"use strict";function outlineTreeConverter(docText){var meta=function(node){return{representativeName:node.name,startPosition:(0,_graphqlLanguageServiceUtils.offsetToPosition)(docText,node.loc.start),endPosition:(0,_graphqlLanguageServiceUtils.offsetToPosition)(docText,node.loc.end),children:node.selectionSet||[]}};return{Field:function(node){var tokenizedText=node.alias?[buildToken("plain",node.alias),buildToken("plain",": ")]:[];return tokenizedText.push(buildToken("plain",node.name)),_extends({tokenizedText:tokenizedText},meta(node))},OperationDefinition:function(node){return _extends({tokenizedText:[buildToken("keyword",node.operation),buildToken("whitespace"," "),buildToken("class-name",node.name)]},meta(node))},Document:function(node){return node.definitions},SelectionSet:function(node){return concatMap(node.selections,function(child){return child.kind===_kinds.INLINE_FRAGMENT?child.selectionSet:child})},Name:function(node){return node.value},FragmentDefinition:function(node){return _extends({tokenizedText:[buildToken("keyword","fragment"),buildToken("whitespace"," "),buildToken("class-name",node.name)]},meta(node))},FragmentSpread:function(node){return _extends({tokenizedText:[buildToken("plain","..."),buildToken("class-name",node.name)]},meta(node))},InlineFragment:function(node){return node.selectionSet}}}function buildToken(kind,value){return{kind:kind,value:value}}function concatMap(arr,fn){for(var res=[],i=0;i<arr.length;i++){var x=fn(arr[i],i);Array.isArray(x)?res.push.apply(res,x):res.push(x)}return res}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target};exports.getOutline=function(queryText){var ast=void 0;try{ast=(0,_graphql.parse)(queryText)}catch(error){return null}var visitorFns=outlineTreeConverter(queryText);return{outlineTrees:(0,_graphql.visit)(ast,{leave:function(node){return OUTLINEABLE_KINDS[node.kind]&&visitorFns[node.kind]?visitorFns[node.kind](node):null}})}};var _graphql=require("graphql"),_kinds=require("graphql/language/kinds"),_graphqlLanguageServiceUtils=require("graphql-language-service-utils"),OUTLINEABLE_KINDS={Field:!0,OperationDefinition:!0,Document:!0,SelectionSet:!0,Name:!0,FragmentDefinition:!0,FragmentSpread:!0,InlineFragment:!0}},{graphql:92,"graphql-language-service-utils":81,"graphql/language/kinds":102}],73:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _autocompleteUtils=require("./autocompleteUtils");Object.defineProperty(exports,"getDefinitionState",{enumerable:!0,get:function(){return _autocompleteUtils.getDefinitionState}}),Object.defineProperty(exports,"getFieldDef",{enumerable:!0,get:function(){return _autocompleteUtils.getFieldDef}}),Object.defineProperty(exports,"forEachState",{enumerable:!0,get:function(){return _autocompleteUtils.forEachState}}),Object.defineProperty(exports,"objectValues",{enumerable:!0,get:function(){return _autocompleteUtils.objectValues}}),Object.defineProperty(exports,"hintList",{enumerable:!0,get:function(){return _autocompleteUtils.hintList}});var _getAutocompleteSuggestions=require("./getAutocompleteSuggestions");Object.defineProperty(exports,"getAutocompleteSuggestions",{enumerable:!0,get:function(){return _getAutocompleteSuggestions.getAutocompleteSuggestions}});var _getDefinition=require("./getDefinition");Object.defineProperty(exports,"LANGUAGE",{enumerable:!0,get:function(){return _getDefinition.LANGUAGE}}),Object.defineProperty(exports,"getDefinitionQueryResultForFragmentSpread",{enumerable:!0,get:function(){return _getDefinition.getDefinitionQueryResultForFragmentSpread}}),Object.defineProperty(exports,"getDefinitionQueryResultForDefinitionNode",{enumerable:!0,get:function(){return _getDefinition.getDefinitionQueryResultForDefinitionNode}});var _getDiagnostics=require("./getDiagnostics");Object.defineProperty(exports,"getDiagnostics",{enumerable:!0,get:function(){return _getDiagnostics.getDiagnostics}});var _getOutline=require("./getOutline");Object.defineProperty(exports,"getOutline",{enumerable:!0,get:function(){return _getOutline.getOutline}});var _GraphQLLanguageService=require("./GraphQLLanguageService");Object.defineProperty(exports,"GraphQLLanguageService",{enumerable:!0,get:function(){return _GraphQLLanguageService.GraphQLLanguageService}})},{"./GraphQLLanguageService":67,"./autocompleteUtils":68,"./getAutocompleteSuggestions":69,"./getDefinition":70,"./getDiagnostics":71,"./getOutline":72}],74:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:!0});var CharacterStream=function(){function CharacterStream(sourceText){var _this=this;_classCallCheck(this,CharacterStream),this.getStartOfToken=function(){return _this._start},this.getCurrentPosition=function(){return _this._pos},this.eol=function(){return _this._sourceText.length===_this._pos},this.sol=function(){return 0===_this._pos},this.peek=function(){return _this._sourceText.charAt(_this._pos)?_this._sourceText.charAt(_this._pos):null},this.next=function(){var char=_this._sourceText.charAt(_this._pos);return _this._pos++,char},this.eat=function(pattern){if(_this._testNextCharacter(pattern))return _this._start=_this._pos,_this._pos++,_this._sourceText.charAt(_this._pos-1)},this.eatWhile=function(match){var isMatched=_this._testNextCharacter(match),didEat=!1;for(isMatched&&(didEat=isMatched,_this._start=_this._pos);isMatched;)_this._pos++,isMatched=_this._testNextCharacter(match),didEat=!0;return didEat},this.eatSpace=function(){return _this.eatWhile(/[\s\u00a0]/)},this.skipToEnd=function(){_this._pos=_this._sourceText.length},this.skipTo=function(position){_this._pos=position},this.match=function(pattern){var consume=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],caseFold=arguments.length>2&&void 0!==arguments[2]&&arguments[2],token=null,match=null;return"string"==typeof pattern?(match=new RegExp(pattern,caseFold?"i":"g").test(_this._sourceText.substr(_this._pos,pattern.length)),token=pattern):pattern instanceof RegExp&&(token=(match=_this._sourceText.slice(_this._pos).match(pattern))&&match[0]),!(null==match||!("string"==typeof pattern||match instanceof Array&&_this._sourceText.startsWith(match[0],_this._pos)))&&(consume&&(_this._start=_this._pos,token&&token.length&&(_this._pos+=token.length)),match)},this.backUp=function(num){_this._pos-=num},this.column=function(){return _this._pos},this.indentation=function(){var match=_this._sourceText.match(/\s*/),indent=0;if(match&&0===match.length)for(var whitespaces=match[0],pos=0;whitespaces.length>pos;)9===whitespaces.charCodeAt(pos)?indent+=2:indent++,pos++;return indent},this.current=function(){return _this._sourceText.slice(_this._start,_this._pos)},this._start=0,this._pos=0,this._sourceText=sourceText}return CharacterStream.prototype._testNextCharacter=function(pattern){var character=this._sourceText.charAt(this._pos);return"string"==typeof pattern?character===pattern:pattern instanceof RegExp?pattern.test(character):pattern(character)},CharacterStream}();exports.default=CharacterStream},{}],75:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.opt=function(ofRule){return{ofRule:ofRule}},exports.list=function(ofRule,separator){return{ofRule:ofRule,isList:!0,separator:separator}},exports.butNot=function(rule,exclusions){var ruleMatch=rule.match;return rule.match=function(token){var check=!1;return ruleMatch&&(check=ruleMatch(token)),check&&exclusions.every(function(exclusion){return exclusion.match&&!exclusion.match(token)})},rule},exports.t=function(kind,style){return{style:style,match:function(token){return token.kind===kind}}},exports.p=function(value,style){return{style:style||"punctuation",match:function(token){return"Punctuation"===token.kind&&token.value===value}}}},{}],76:[function(require,module,exports){"use strict";function word(value){return{style:"keyword",match:function(token){return"Name"===token.kind&&token.value===value}}}function name(style){return{style:style,match:function(token){return"Name"===token.kind},update:function(state,token){state.name=token.value}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ParseRules=exports.LexRules=exports.isIgnored=void 0;var _RuleHelpers=require("./RuleHelpers");exports.isIgnored=function(ch){return" "===ch||"\t"===ch||","===ch||"\n"===ch||"\r"===ch||"\ufeff"===ch},exports.LexRules={Name:/^[_A-Za-z][_0-9A-Za-z]*/,Punctuation:/^(?:!|\$|\(|\)|\.\.\.|:|=|@|\[|]|\{|\||\})/,Number:/^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,String:/^"(?:[^"\\]|\\(?:"|\/|\\|b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/,Comment:/^#.*/},exports.ParseRules={Document:[(0,_RuleHelpers.list)("Definition")],Definition:function(token){switch(token.value){case"{":return"ShortQuery";case"query":return"Query";case"mutation":return"Mutation";case"subscription":return"Subscription";case"fragment":return"FragmentDefinition";case"schema":return"SchemaDef";case"scalar":return"ScalarDef";case"type":return"ObjectTypeDef";case"interface":return"InterfaceDef";case"union":return"UnionDef";case"enum":return"EnumDef";case"input":return"InputDef";case"extend":return"ExtendDef";case"directive":return"DirectiveDef"}},ShortQuery:["SelectionSet"],Query:[word("query"),(0,_RuleHelpers.opt)(name("def")),(0,_RuleHelpers.opt)("VariableDefinitions"),(0,_RuleHelpers.list)("Directive"),"SelectionSet"],Mutation:[word("mutation"),(0,_RuleHelpers.opt)(name("def")),(0,_RuleHelpers.opt)("VariableDefinitions"),(0,_RuleHelpers.list)("Directive"),"SelectionSet"],Subscription:[word("subscription"),(0,_RuleHelpers.opt)(name("def")),(0,_RuleHelpers.opt)("VariableDefinitions"),(0,_RuleHelpers.list)("Directive"),"SelectionSet"],VariableDefinitions:[(0,_RuleHelpers.p)("("),(0,_RuleHelpers.list)("VariableDefinition"),(0,_RuleHelpers.p)(")")],VariableDefinition:["Variable",(0,_RuleHelpers.p)(":"),"Type",(0,_RuleHelpers.opt)("DefaultValue")],Variable:[(0,_RuleHelpers.p)("$","variable"),name("variable")],DefaultValue:[(0,_RuleHelpers.p)("="),"Value"],SelectionSet:[(0,_RuleHelpers.p)("{"),(0,_RuleHelpers.list)("Selection"),(0,_RuleHelpers.p)("}")],Selection:function(token,stream){return"..."===token.value?stream.match(/[\s\u00a0,]*(on\b|@|{)/,!1)?"InlineFragment":"FragmentSpread":stream.match(/[\s\u00a0,]*:/,!1)?"AliasedField":"Field"},AliasedField:[name("property"),(0,_RuleHelpers.p)(":"),name("qualifier"),(0,_RuleHelpers.opt)("Arguments"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.opt)("SelectionSet")],Field:[name("property"),(0,_RuleHelpers.opt)("Arguments"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.opt)("SelectionSet")],Arguments:[(0,_RuleHelpers.p)("("),(0,_RuleHelpers.list)("Argument"),(0,_RuleHelpers.p)(")")],Argument:[name("attribute"),(0,_RuleHelpers.p)(":"),"Value"],FragmentSpread:[(0,_RuleHelpers.p)("..."),name("def"),(0,_RuleHelpers.list)("Directive")],InlineFragment:[(0,_RuleHelpers.p)("..."),(0,_RuleHelpers.opt)("TypeCondition"),(0,_RuleHelpers.list)("Directive"),"SelectionSet"],FragmentDefinition:[word("fragment"),(0,_RuleHelpers.opt)((0,_RuleHelpers.butNot)(name("def"),[word("on")])),"TypeCondition",(0,_RuleHelpers.list)("Directive"),"SelectionSet"],TypeCondition:[word("on"),"NamedType"],Value:function(token){switch(token.kind){case"Number":return"NumberValue";case"String":return"StringValue";case"Punctuation":switch(token.value){case"[":return"ListValue";case"{":return"ObjectValue";case"$":return"Variable"}return null;case"Name":switch(token.value){case"true":case"false":return"BooleanValue"}return"null"===token.value?"NullValue":"EnumValue"}},NumberValue:[(0,_RuleHelpers.t)("Number","number")],StringValue:[(0,_RuleHelpers.t)("String","string")],BooleanValue:[(0,_RuleHelpers.t)("Name","builtin")],NullValue:[(0,_RuleHelpers.t)("Name","keyword")],EnumValue:[name("string-2")],ListValue:[(0,_RuleHelpers.p)("["),(0,_RuleHelpers.list)("Value"),(0,_RuleHelpers.p)("]")],ObjectValue:[(0,_RuleHelpers.p)("{"),(0,_RuleHelpers.list)("ObjectField"),(0,_RuleHelpers.p)("}")],ObjectField:[name("attribute"),(0,_RuleHelpers.p)(":"),"Value"],Type:function(token){return"["===token.value?"ListType":"NonNullType"},ListType:[(0,_RuleHelpers.p)("["),"Type",(0,_RuleHelpers.p)("]"),(0,_RuleHelpers.opt)((0,_RuleHelpers.p)("!"))],NonNullType:["NamedType",(0,_RuleHelpers.opt)((0,_RuleHelpers.p)("!"))],NamedType:[{style:"atom",match:function(token){return"Name"===token.kind},update:function(state,token){state.prevState&&state.prevState.prevState&&(state.name=token.value,state.prevState.prevState.type=token.value)}}],Directive:[(0,_RuleHelpers.p)("@","meta"),name("meta"),(0,_RuleHelpers.opt)("Arguments")],SchemaDef:[word("schema"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.p)("{"),(0,_RuleHelpers.list)("OperationTypeDef"),(0,_RuleHelpers.p)("}")],OperationTypeDef:[name("keyword"),(0,_RuleHelpers.p)(":"),name("atom")],ScalarDef:[word("scalar"),name("atom"),(0,_RuleHelpers.list)("Directive")],ObjectTypeDef:[word("type"),name("atom"),(0,_RuleHelpers.opt)("Implements"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.p)("{"),(0,_RuleHelpers.list)("FieldDef"),(0,_RuleHelpers.p)("}")],Implements:[word("implements"),(0,_RuleHelpers.list)("NamedType")],FieldDef:[name("property"),(0,_RuleHelpers.opt)("ArgumentsDef"),(0,_RuleHelpers.p)(":"),"Type",(0,_RuleHelpers.list)("Directive")],ArgumentsDef:[(0,_RuleHelpers.p)("("),(0,_RuleHelpers.list)("InputValueDef"),(0,_RuleHelpers.p)(")")],InputValueDef:[name("attribute"),(0,_RuleHelpers.p)(":"),"Type",(0,_RuleHelpers.opt)("DefaultValue"),(0,_RuleHelpers.list)("Directive")],InterfaceDef:[word("interface"),name("atom"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.p)("{"),(0,_RuleHelpers.list)("FieldDef"),(0,_RuleHelpers.p)("}")],UnionDef:[word("union"),name("atom"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.p)("="),(0,_RuleHelpers.list)("UnionMember",(0,_RuleHelpers.p)("|"))],UnionMember:["NamedType"],EnumDef:[word("enum"),name("atom"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.p)("{"),(0,_RuleHelpers.list)("EnumValueDef"),(0,_RuleHelpers.p)("}")],EnumValueDef:[name("string-2"),(0,_RuleHelpers.list)("Directive")],InputDef:[word("input"),name("atom"),(0,_RuleHelpers.list)("Directive"),(0,_RuleHelpers.p)("{"),(0,_RuleHelpers.list)("InputValueDef"),(0,_RuleHelpers.p)("}")],ExtendDef:[word("extend"),"ObjectTypeDef"],DirectiveDef:[word("directive"),(0,_RuleHelpers.p)("@","meta"),name("meta"),(0,_RuleHelpers.opt)("ArgumentsDef"),word("on"),(0,_RuleHelpers.list)("DirectiveLocation",(0,_RuleHelpers.p)("|"))],DirectiveLocation:[name("string-2")]}},{"./RuleHelpers":75}],77:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(exports,"__esModule",{value:!0});var _CharacterStream=require("./CharacterStream");Object.defineProperty(exports,"CharacterStream",{enumerable:!0,get:function(){return _interopRequireDefault(_CharacterStream).default}});var _Rules=require("./Rules");Object.defineProperty(exports,"LexRules",{enumerable:!0,get:function(){return _Rules.LexRules}}),Object.defineProperty(exports,"ParseRules",{enumerable:!0,get:function(){return _Rules.ParseRules}}),Object.defineProperty(exports,"isIgnored",{enumerable:!0,get:function(){return _Rules.isIgnored}});var _RuleHelpers=require("./RuleHelpers");Object.defineProperty(exports,"butNot",{enumerable:!0,get:function(){return _RuleHelpers.butNot}}),Object.defineProperty(exports,"list",{enumerable:!0,get:function(){return _RuleHelpers.list}}),Object.defineProperty(exports,"opt",{enumerable:!0,get:function(){return _RuleHelpers.opt}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return _RuleHelpers.p}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return _RuleHelpers.t}});var _onlineParser=require("./onlineParser");Object.defineProperty(exports,"onlineParser",{enumerable:!0,get:function(){return _interopRequireDefault(_onlineParser).default}})},{"./CharacterStream":74,"./RuleHelpers":75,"./Rules":76,"./onlineParser":78}],78:[function(require,module,exports){"use strict";function getToken(stream,state,options){var lexRules=options.lexRules,parseRules=options.parseRules,eatWhitespace=options.eatWhitespace,editorConfig=options.editorConfig;if(state.rule&&0===state.rule.length?popRule(state):state.needsAdvance&&(state.needsAdvance=!1,advanceRule(state,!0)),stream.sol()){var tabSize=editorConfig&&editorConfig.tabSize||2;state.indentLevel=Math.floor(stream.indentation()/tabSize)}if(eatWhitespace(stream))return"ws";var token=lex(lexRules,stream);if(!token)return stream.match(/\S+/),pushRule(SpecialParseRules,state,"Invalid"),"invalidchar";if("Comment"===token.kind)return pushRule(SpecialParseRules,state,"Comment"),"comment";var backupState=assign({},state);if("Punctuation"===token.kind)if(/^[{([]/.test(token.value))state.levels=(state.levels||[]).concat(state.indentLevel+1);else if(/^[})\]]/.test(token.value)){var levels=state.levels=(state.levels||[]).slice(0,-1);state.indentLevel&&levels.length>0&&levels[levels.length-1]<state.indentLevel&&(state.indentLevel=levels[levels.length-1])}for(;state.rule;){var expected="function"==typeof state.rule?0===state.step?state.rule(token,stream):null:state.rule[state.step];if(state.needsSeperator&&(expected=expected&&expected.separator),expected){if(expected.ofRule&&(expected=expected.ofRule),"string"==typeof expected){pushRule(parseRules,state,expected);continue}if(expected.match&&expected.match(token))return expected.update&&expected.update(state,token),"Punctuation"===token.kind?advanceRule(state,!0):state.needsAdvance=!0,expected.style}unsuccessful(state)}return assign(state,backupState),pushRule(SpecialParseRules,state,"Invalid"),"invalidchar"}function assign(to,from){for(var keys=Object.keys(from),i=0;i<keys.length;i++)to[keys[i]]=from[keys[i]];return to}function pushRule(rules,state,ruleKind){if(!rules[ruleKind])throw new TypeError("Unknown rule: "+ruleKind);state.prevState=_extends({},state),state.kind=ruleKind,state.name=null,state.type=null,state.rule=rules[ruleKind],state.step=0,state.needsSeperator=!1}function popRule(state){state.prevState&&(state.kind=state.prevState.kind,state.name=state.prevState.name,state.type=state.prevState.type,state.rule=state.prevState.rule,state.step=state.prevState.step,state.needsSeperator=state.prevState.needsSeperator,state.prevState=state.prevState.prevState)}function advanceRule(state,successful){if(isList(state)){if(state.rule&&state.rule[state.step].separator){var separator=state.rule[state.step].separator;if(state.needsSeperator=!state.needsSeperator,!state.needsSeperator&&separator.ofRule)return}if(successful)return}for(state.needsSeperator=!1,state.step++;state.rule&&!(Array.isArray(state.rule)&&state.step<state.rule.length);)popRule(state),state.rule&&(isList(state)?state.rule&&state.rule[state.step].separator&&(state.needsSeperator=!state.needsSeperator):(state.needsSeperator=!1,state.step++))}function isList(state){return Array.isArray(state.rule)&&"string"!=typeof state.rule[state.step]&&state.rule[state.step].isList}function unsuccessful(state){for(;state.rule&&(!Array.isArray(state.rule)||!state.rule[state.step].ofRule);)popRule(state);state.rule&&advanceRule(state,!1)}function lex(lexRules,stream){for(var kinds=Object.keys(lexRules),i=0;i<kinds.length;i++){var match=stream.match(lexRules[kinds[i]]);if(match&&match instanceof Array)return{kind:kinds[i],value:match[0]}}}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target};exports.default=function(){var options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{eatWhitespace:function(stream){return stream.eatWhile(_Rules.isIgnored)},lexRules:_Rules.LexRules,parseRules:_Rules.ParseRules,editorConfig:{}};return{startState:function(){var initialState={level:0,step:0,name:null,kind:null,type:null,rule:null,needsSeperator:!1,prevState:null};return pushRule(options.parseRules,initialState,"Document"),initialState},token:function(stream,state){return getToken(stream,state,options)}}};var _Rules=require("./Rules"),SpecialParseRules={Invalid:[],Comment:[]}},{"./Rules":76}],79:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function offsetToPosition(text,loc){var buf=text.slice(0,loc),lines=buf.split("\n").length-1,lastLineIndex=buf.lastIndexOf("\n");return new Position(lines,loc-lastLineIndex-1)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.offsetToPosition=offsetToPosition,exports.locToRange=function(text,loc){var start=offsetToPosition(text,loc.start),end=offsetToPosition(text,loc.end);return new Range(start,end)};var Range=exports.Range=function(){function Range(start,end){var _this=this;_classCallCheck(this,Range),this.containsPosition=function(position){return _this.start.line===position.line?_this.start.character<=position.character:_this.end.line===position.line?_this.end.character>=position.character:_this.start.line<=position.line&&_this.end.line>=position.line},this.start=start,this.end=end}return Range.prototype.setStart=function(line,character){this.start=new Position(line,character)},Range.prototype.setEnd=function(line,character){this.end=new Position(line,character)},Range}(),Position=exports.Position=function(){function Position(line,character){var _this2=this;_classCallCheck(this,Position),this.lessThanOrEqualTo=function(position){return _this2.line<position.line||_this2.line===position.line&&_this2.character<=position.character},this.line=line,this.character=character}return Position.prototype.setLine=function(line){this.line=line},Position.prototype.setCharacter=function(character){this.character=character},Position}()},{}],80:[function(require,module,exports){"use strict";function pointToOffset(text,point){var linesUntilPosition=text.split("\n").slice(0,point.line);return point.character+linesUntilPosition.map(function(line){return line.length+1}).reduce(function(a,b){return a+b},0)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getASTNodeAtPosition=function(query,ast,point){var offset=pointToOffset(query,point),nodeContainingPosition=void 0;return(0,_graphql.visit)(ast,{enter:function(node){if(!("Name"!==node.kind&&node.loc.start<=offset&&offset<=node.loc.end))return!1;nodeContainingPosition=node},leave:function(node){if(node.loc.start<=offset&&offset<=node.loc.end)return!1}}),nodeContainingPosition},exports.pointToOffset=pointToOffset;require("./Range");var _graphql=require("graphql")},{"./Range":79,graphql:92}],81:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _getASTNodeAtPosition=require("./getASTNodeAtPosition");Object.defineProperty(exports,"getASTNodeAtPosition",{enumerable:!0,get:function(){return _getASTNodeAtPosition.getASTNodeAtPosition}}),Object.defineProperty(exports,"pointToOffset",{enumerable:!0,get:function(){return _getASTNodeAtPosition.pointToOffset}});var _Range=require("./Range");Object.defineProperty(exports,"Position",{enumerable:!0,get:function(){return _Range.Position}}),Object.defineProperty(exports,"Range",{enumerable:!0,get:function(){return _Range.Range}}),Object.defineProperty(exports,"locToRange",{enumerable:!0,get:function(){return _Range.locToRange}}),Object.defineProperty(exports,"offsetToPosition",{enumerable:!0,get:function(){return _Range.offsetToPosition}});var _validateWithCustomRules=require("./validateWithCustomRules");Object.defineProperty(exports,"validateWithCustomRules",{enumerable:!0,get:function(){return _validateWithCustomRules.validateWithCustomRules}})},{"./Range":79,"./getASTNodeAtPosition":80,"./validateWithCustomRules":82}],82:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateWithCustomRules=function(schema,ast,customRules){var NoUnusedFragments=require("graphql/validation/rules/NoUnusedFragments").NoUnusedFragments,rules=_graphql.specifiedRules.filter(function(rule){return rule!==NoUnusedFragments}),typeInfo=new _graphql.TypeInfo(schema);customRules&&Array.prototype.push.apply(rules,customRules);var errors=(0,_graphql.validate)(schema,ast,rules,typeInfo);return errors.length>0?errors:[]};var _graphql=require("graphql")},{graphql:92,"graphql/validation/rules/NoUnusedFragments":149}],83:[function(require,module,exports){"use strict";function GraphQLError(message,nodes,source,positions,path,originalError){var _source=source;if(!_source&&nodes&&nodes.length>0){var node=nodes[0];_source=node&&node.loc&&node.loc.source}var _positions=positions;!_positions&&nodes&&(_positions=nodes.filter(function(node){return Boolean(node.loc)}).map(function(node){return node.loc.start})),_positions&&0===_positions.length&&(_positions=void 0);var _locations=void 0,_source2=_source;_source2&&_positions&&(_locations=_positions.map(function(pos){return(0,_location.getLocation)(_source2,pos)})),Object.defineProperties(this,{message:{value:message,enumerable:!0,writable:!0},locations:{value:_locations||void 0,enumerable:!0},path:{value:path||void 0,enumerable:!0},nodes:{value:nodes||void 0},source:{value:_source||void 0},positions:{value:_positions||void 0},originalError:{value:originalError}}),originalError&&originalError.stack?Object.defineProperty(this,"stack",{value:originalError.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,GraphQLError):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLError=GraphQLError;var _location=require("../language/location");GraphQLError.prototype=Object.create(Error.prototype,{constructor:{value:GraphQLError},name:{value:"GraphQLError"}})},{"../language/location":104}],84:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatError=function(error){return(0,_invariant2.default)(error,"Received null or undefined error."),{message:error.message,locations:error.locations,path:error.path}};var _invariant2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../jsutils/invariant"))},{"../jsutils/invariant":94}],85:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _GraphQLError=require("./GraphQLError");Object.defineProperty(exports,"GraphQLError",{enumerable:!0,get:function(){return _GraphQLError.GraphQLError}});var _syntaxError=require("./syntaxError");Object.defineProperty(exports,"syntaxError",{enumerable:!0,get:function(){return _syntaxError.syntaxError}});var _locatedError=require("./locatedError");Object.defineProperty(exports,"locatedError",{enumerable:!0,get:function(){return _locatedError.locatedError}});var _formatError=require("./formatError");Object.defineProperty(exports,"formatError",{enumerable:!0,get:function(){return _formatError.formatError}})},{"./GraphQLError":83,"./formatError":84,"./locatedError":86,"./syntaxError":87}],86:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.locatedError=function(originalError,nodes,path){if(originalError&&originalError.path)return originalError;var message=originalError?originalError.message||String(originalError):"An unknown error occurred.";return new _GraphQLError.GraphQLError(message,originalError&&originalError.nodes||nodes,originalError&&originalError.source,originalError&&originalError.positions,path,originalError)};var _GraphQLError=require("./GraphQLError")},{"./GraphQLError":83}],87:[function(require,module,exports){"use strict";function highlightSourceAtLocation(source,location){var line=location.line,prevLineNum=(line-1).toString(),lineNum=line.toString(),nextLineNum=(line+1).toString(),padLen=nextLineNum.length,lines=source.body.split(/\r\n|[\n\r]/g);return(line>=2?lpad(padLen,prevLineNum)+": "+lines[line-2]+"\n":"")+lpad(padLen,lineNum)+": "+lines[line-1]+"\n"+Array(2+padLen+location.column).join(" ")+"^\n"+(line<lines.length?lpad(padLen,nextLineNum)+": "+lines[line]+"\n":"")}function lpad(len,str){return Array(len-str.length+1).join(" ")+str}Object.defineProperty(exports,"__esModule",{value:!0}),exports.syntaxError=function(source,position,description){var location=(0,_location.getLocation)(source,position);return new _GraphQLError.GraphQLError("Syntax Error "+source.name+" ("+location.line+":"+location.column+") "+description+"\n\n"+highlightSourceAtLocation(source,location),void 0,source,[position])};var _location=require("../language/location"),_GraphQLError=require("./GraphQLError")},{"../language/location":104,"./GraphQLError":83}],88:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function executeImpl(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver){assertValidExecutionArguments(schema,document,variableValues);var context=void 0;try{context=buildExecutionContext(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver)}catch(error){return Promise.resolve({errors:[error]})}return Promise.resolve(executeOperation(context,context.operation,rootValue)).then(function(data){return 0===context.errors.length?{data:data}:{errors:context.errors,data:data}})}function responsePathAsArray(path){for(var flattened=[],curr=path;curr;)flattened.push(curr.key),curr=curr.prev;return flattened.reverse()}function addPath(prev,key){return{prev:prev,key:key}}function assertValidExecutionArguments(schema,document,rawVariableValues){(0,_invariant2.default)(schema,"Must provide schema"),(0,_invariant2.default)(document,"Must provide document"),(0,_invariant2.default)(schema instanceof _schema.GraphQLSchema,"Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory."),(0,_invariant2.default)(!rawVariableValues||"object"==typeof rawVariableValues,"Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.")}function buildExecutionContext(schema,document,rootValue,contextValue,rawVariableValues,operationName,fieldResolver){var errors=[],operation=void 0,fragments=Object.create(null);if(document.definitions.forEach(function(definition){switch(definition.kind){case Kind.OPERATION_DEFINITION:if(!operationName&&operation)throw new _error.GraphQLError("Must provide operation name if query contains multiple operations.");(!operationName||definition.name&&definition.name.value===operationName)&&(operation=definition);break;case Kind.FRAGMENT_DEFINITION:fragments[definition.name.value]=definition;break;default:throw new _error.GraphQLError("GraphQL cannot execute a request containing a "+definition.kind+".",[definition])}}),!operation)throw operationName?new _error.GraphQLError('Unknown operation named "'+operationName+'".'):new _error.GraphQLError("Must provide an operation.");var variableValues=(0,_values.getVariableValues)(schema,operation.variableDefinitions||[],rawVariableValues||{});return{schema:schema,fragments:fragments,rootValue:rootValue,contextValue:contextValue,operation:operation,variableValues:variableValues,fieldResolver:fieldResolver||defaultFieldResolver,errors:errors}}function executeOperation(exeContext,operation,rootValue){var type=getOperationRootType(exeContext.schema,operation),fields=collectFields(exeContext,type,operation.selectionSet,Object.create(null),Object.create(null));try{var result="mutation"===operation.operation?executeFieldsSerially(exeContext,type,rootValue,void 0,fields):executeFields(exeContext,type,rootValue,void 0,fields),promise=getPromise(result);return promise?promise.then(void 0,function(error){return exeContext.errors.push(error),Promise.resolve(null)}):result}catch(error){return exeContext.errors.push(error),null}}function getOperationRootType(schema,operation){switch(operation.operation){case"query":return schema.getQueryType();case"mutation":var mutationType=schema.getMutationType();if(!mutationType)throw new _error.GraphQLError("Schema is not configured for mutations",[operation]);return mutationType;case"subscription":var subscriptionType=schema.getSubscriptionType();if(!subscriptionType)throw new _error.GraphQLError("Schema is not configured for subscriptions",[operation]);return subscriptionType;default:throw new _error.GraphQLError("Can only execute queries, mutations and subscriptions",[operation])}}function executeFieldsSerially(exeContext,parentType,sourceValue,path,fields){return Object.keys(fields).reduce(function(prevPromise,responseName){return prevPromise.then(function(results){var fieldNodes=fields[responseName],fieldPath=addPath(path,responseName),result=resolveField(exeContext,parentType,sourceValue,fieldNodes,fieldPath);if(void 0===result)return results;var promise=getPromise(result);return promise?promise.then(function(resolvedResult){return results[responseName]=resolvedResult,results}):(results[responseName]=result,results)})},Promise.resolve({}))}function executeFields(exeContext,parentType,sourceValue,path,fields){var containsPromise=!1,finalResults=Object.keys(fields).reduce(function(results,responseName){var fieldNodes=fields[responseName],fieldPath=addPath(path,responseName),result=resolveField(exeContext,parentType,sourceValue,fieldNodes,fieldPath);return void 0===result?results:(results[responseName]=result,getPromise(result)&&(containsPromise=!0),results)},Object.create(null));return containsPromise?promiseForObject(finalResults):finalResults}function collectFields(exeContext,runtimeType,selectionSet,fields,visitedFragmentNames){for(var i=0;i<selectionSet.selections.length;i++){var selection=selectionSet.selections[i];switch(selection.kind){case Kind.FIELD:if(!shouldIncludeNode(exeContext,selection))continue;var _name=getFieldEntryKey(selection);fields[_name]||(fields[_name]=[]),fields[_name].push(selection);break;case Kind.INLINE_FRAGMENT:if(!shouldIncludeNode(exeContext,selection)||!doesFragmentConditionMatch(exeContext,selection,runtimeType))continue;collectFields(exeContext,runtimeType,selection.selectionSet,fields,visitedFragmentNames);break;case Kind.FRAGMENT_SPREAD:var fragName=selection.name.value;if(visitedFragmentNames[fragName]||!shouldIncludeNode(exeContext,selection))continue;visitedFragmentNames[fragName]=!0;var fragment=exeContext.fragments[fragName];if(!fragment||!doesFragmentConditionMatch(exeContext,fragment,runtimeType))continue;collectFields(exeContext,runtimeType,fragment.selectionSet,fields,visitedFragmentNames)}}return fields}function shouldIncludeNode(exeContext,node){var skip=(0,_values.getDirectiveValues)(_directives.GraphQLSkipDirective,node,exeContext.variableValues);if(skip&&!0===skip.if)return!1;var include=(0,_values.getDirectiveValues)(_directives.GraphQLIncludeDirective,node,exeContext.variableValues);return!include||!1!==include.if}function doesFragmentConditionMatch(exeContext,fragment,type){var typeConditionNode=fragment.typeCondition;if(!typeConditionNode)return!0;var conditionalType=(0,_typeFromAST.typeFromAST)(exeContext.schema,typeConditionNode);return conditionalType===type||!!(0,_definition.isAbstractType)(conditionalType)&&exeContext.schema.isPossibleType(conditionalType,type)}function promiseForObject(object){var keys=Object.keys(object),valuesAndPromises=keys.map(function(name){return object[name]});return Promise.all(valuesAndPromises).then(function(values){return values.reduce(function(resolvedObject,value,i){return resolvedObject[keys[i]]=value,resolvedObject},Object.create(null))})}function getFieldEntryKey(node){return node.alias?node.alias.value:node.name.value}function resolveField(exeContext,parentType,source,fieldNodes,path){var fieldName=fieldNodes[0].name.value,fieldDef=getFieldDef(exeContext.schema,parentType,fieldName);if(fieldDef){var resolveFn=fieldDef.resolve||exeContext.fieldResolver,info=buildResolveInfo(exeContext,fieldDef,fieldNodes,parentType,path),result=resolveFieldValueOrError(exeContext,fieldDef,fieldNodes,resolveFn,source,info);return completeValueCatchingError(exeContext,fieldDef.type,fieldNodes,info,path,result)}}function buildResolveInfo(exeContext,fieldDef,fieldNodes,parentType,path){return{fieldName:fieldNodes[0].name.value,fieldNodes:fieldNodes,returnType:fieldDef.type,parentType:parentType,path:path,schema:exeContext.schema,fragments:exeContext.fragments,rootValue:exeContext.rootValue,operation:exeContext.operation,variableValues:exeContext.variableValues}}function resolveFieldValueOrError(exeContext,fieldDef,fieldNodes,resolveFn,source,info){try{return resolveFn(source,(0,_values.getArgumentValues)(fieldDef,fieldNodes[0],exeContext.variableValues),exeContext.contextValue,info)}catch(error){return error instanceof Error?error:new Error(error)}}function completeValueCatchingError(exeContext,returnType,fieldNodes,info,path,result){if(returnType instanceof _definition.GraphQLNonNull)return completeValueWithLocatedError(exeContext,returnType,fieldNodes,info,path,result);try{var completed=completeValueWithLocatedError(exeContext,returnType,fieldNodes,info,path,result),promise=getPromise(completed);return promise?promise.then(void 0,function(error){return exeContext.errors.push(error),Promise.resolve(null)}):completed}catch(error){return exeContext.errors.push(error),null}}function completeValueWithLocatedError(exeContext,returnType,fieldNodes,info,path,result){try{var completed=completeValue(exeContext,returnType,fieldNodes,info,path,result),promise=getPromise(completed);return promise?promise.then(void 0,function(error){return Promise.reject((0,_error.locatedError)(error,fieldNodes,responsePathAsArray(path)))}):completed}catch(error){throw(0,_error.locatedError)(error,fieldNodes,responsePathAsArray(path))}}function completeValue(exeContext,returnType,fieldNodes,info,path,result){var promise=getPromise(result);if(promise)return promise.then(function(resolved){return completeValue(exeContext,returnType,fieldNodes,info,path,resolved)});if(result instanceof Error)throw result;if(returnType instanceof _definition.GraphQLNonNull){var completed=completeValue(exeContext,returnType.ofType,fieldNodes,info,path,result);if(null===completed)throw new Error("Cannot return null for non-nullable field "+info.parentType.name+"."+info.fieldName+".");return completed}if((0,_isNullish2.default)(result))return null;if(returnType instanceof _definition.GraphQLList)return completeListValue(exeContext,returnType,fieldNodes,info,path,result);if((0,_definition.isLeafType)(returnType))return completeLeafValue(returnType,result);if((0,_definition.isAbstractType)(returnType))return completeAbstractValue(exeContext,returnType,fieldNodes,info,path,result);if(returnType instanceof _definition.GraphQLObjectType)return completeObjectValue(exeContext,returnType,fieldNodes,info,path,result);throw new Error('Cannot complete value of unexpected type "'+String(returnType)+'".')}function completeListValue(exeContext,returnType,fieldNodes,info,path,result){(0,_invariant2.default)((0,_iterall.isCollection)(result),"Expected Iterable, but did not find one for field "+info.parentType.name+"."+info.fieldName+".");var itemType=returnType.ofType,containsPromise=!1,completedResults=[];return(0,_iterall.forEach)(result,function(item,index){var fieldPath=addPath(path,index),completedItem=completeValueCatchingError(exeContext,itemType,fieldNodes,info,fieldPath,item);!containsPromise&&getPromise(completedItem)&&(containsPromise=!0),completedResults.push(completedItem)}),containsPromise?Promise.all(completedResults):completedResults}function completeLeafValue(returnType,result){(0,_invariant2.default)(returnType.serialize,"Missing serialize method on type");var serializedResult=returnType.serialize(result);if((0,_isNullish2.default)(serializedResult))throw new Error('Expected a value of type "'+String(returnType)+'" but received: '+String(result));return serializedResult}function completeAbstractValue(exeContext,returnType,fieldNodes,info,path,result){var runtimeType=returnType.resolveType?returnType.resolveType(result,exeContext.contextValue,info):defaultResolveTypeFn(result,exeContext.contextValue,info,returnType),promise=getPromise(runtimeType);return promise?promise.then(function(resolvedRuntimeType){return completeObjectValue(exeContext,ensureValidRuntimeType(resolvedRuntimeType,exeContext,returnType,fieldNodes,info,result),fieldNodes,info,path,result)}):completeObjectValue(exeContext,ensureValidRuntimeType(runtimeType,exeContext,returnType,fieldNodes,info,result),fieldNodes,info,path,result)}function ensureValidRuntimeType(runtimeTypeOrName,exeContext,returnType,fieldNodes,info,result){var runtimeType="string"==typeof runtimeTypeOrName?exeContext.schema.getType(runtimeTypeOrName):runtimeTypeOrName;if(!(runtimeType instanceof _definition.GraphQLObjectType))throw new _error.GraphQLError("Abstract type "+returnType.name+" must resolve to an Object type at runtime for field "+info.parentType.name+"."+info.fieldName+' with value "'+String(result)+'", received "'+String(runtimeType)+'".',fieldNodes);if(!exeContext.schema.isPossibleType(returnType,runtimeType))throw new _error.GraphQLError('Runtime Object type "'+runtimeType.name+'" is not a possible type for "'+returnType.name+'".',fieldNodes);return runtimeType}function completeObjectValue(exeContext,returnType,fieldNodes,info,path,result){if(returnType.isTypeOf){var isTypeOf=returnType.isTypeOf(result,exeContext.contextValue,info),promise=getPromise(isTypeOf);if(promise)return promise.then(function(isTypeOfResult){if(!isTypeOfResult)throw invalidReturnTypeError(returnType,result,fieldNodes);return collectAndExecuteSubfields(exeContext,returnType,fieldNodes,info,path,result)});if(!isTypeOf)throw invalidReturnTypeError(returnType,result,fieldNodes)}return collectAndExecuteSubfields(exeContext,returnType,fieldNodes,info,path,result)}function invalidReturnTypeError(returnType,result,fieldNodes){return new _error.GraphQLError('Expected value of type "'+returnType.name+'" but got: '+String(result)+".",fieldNodes)}function collectAndExecuteSubfields(exeContext,returnType,fieldNodes,info,path,result){for(var subFieldNodes=Object.create(null),visitedFragmentNames=Object.create(null),i=0;i<fieldNodes.length;i++){var selectionSet=fieldNodes[i].selectionSet;selectionSet&&(subFieldNodes=collectFields(exeContext,returnType,selectionSet,subFieldNodes,visitedFragmentNames))}return executeFields(exeContext,returnType,result,path,subFieldNodes)}function defaultResolveTypeFn(value,context,info,abstractType){for(var possibleTypes=info.schema.getPossibleTypes(abstractType),promisedIsTypeOfResults=[],i=0;i<possibleTypes.length;i++){var type=possibleTypes[i];if(type.isTypeOf){var isTypeOfResult=type.isTypeOf(value,context,info),promise=getPromise(isTypeOfResult);if(promise)promisedIsTypeOfResults[i]=promise;else if(isTypeOfResult)return type}}if(promisedIsTypeOfResults.length)return Promise.all(promisedIsTypeOfResults).then(function(isTypeOfResults){for(var _i=0;_i<isTypeOfResults.length;_i++)if(isTypeOfResults[_i])return possibleTypes[_i]})}function getPromise(value){if("object"==typeof value&&null!==value&&"function"==typeof value.then)return value}function getFieldDef(schema,parentType,fieldName){return fieldName===_introspection.SchemaMetaFieldDef.name&&schema.getQueryType()===parentType?_introspection.SchemaMetaFieldDef:fieldName===_introspection.TypeMetaFieldDef.name&&schema.getQueryType()===parentType?_introspection.TypeMetaFieldDef:fieldName===_introspection.TypeNameMetaFieldDef.name?_introspection.TypeNameMetaFieldDef:parentType.getFields()[fieldName]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.defaultFieldResolver=void 0,exports.execute=function(argsOrSchema,document,rootValue,contextValue,variableValues,operationName,fieldResolver){var args=1===arguments.length?argsOrSchema:void 0,schema=args?args.schema:argsOrSchema;return args?executeImpl(schema,args.document,args.rootValue,args.contextValue,args.variableValues,args.operationName,args.fieldResolver):executeImpl(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver)},exports.responsePathAsArray=responsePathAsArray,exports.addPath=addPath,exports.assertValidExecutionArguments=assertValidExecutionArguments,exports.buildExecutionContext=buildExecutionContext,exports.getOperationRootType=getOperationRootType,exports.collectFields=collectFields,exports.buildResolveInfo=buildResolveInfo,exports.resolveFieldValueOrError=resolveFieldValueOrError,exports.getFieldDef=getFieldDef;var _iterall=require("iterall"),_error=require("../error"),_invariant2=_interopRequireDefault(require("../jsutils/invariant")),_isNullish2=_interopRequireDefault(require("../jsutils/isNullish")),_typeFromAST=require("../utilities/typeFromAST"),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_values=require("./values"),_definition=require("../type/definition"),_schema=require("../type/schema"),_introspection=require("../type/introspection"),_directives=require("../type/directives"),defaultFieldResolver=exports.defaultFieldResolver=function(source,args,context,info){if("object"==typeof source||"function"==typeof source){var property=source[info.fieldName];return"function"==typeof property?source[info.fieldName](args,context,info):property}}},{"../error":85,"../jsutils/invariant":94,"../jsutils/isNullish":96,"../language/kinds":102,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/schema":117,"../utilities/typeFromAST":135,"./values":90,iterall:166}],89:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _execute=require("./execute");Object.defineProperty(exports,"execute",{enumerable:!0,get:function(){return _execute.execute}}),Object.defineProperty(exports,"defaultFieldResolver",{enumerable:!0,get:function(){return _execute.defaultFieldResolver}}),Object.defineProperty(exports,"responsePathAsArray",{enumerable:!0,get:function(){return _execute.responsePathAsArray}});var _values=require("./values");Object.defineProperty(exports,"getDirectiveValues",{enumerable:!0,get:function(){return _values.getDirectiveValues}})},{"./execute":88,"./values":90}],90:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function getArgumentValues(def,node,variableValues){var argDefs=def.args,argNodes=node.arguments;if(!argDefs||!argNodes)return{};for(var coercedValues=Object.create(null),argNodeMap=(0,_keyMap2.default)(argNodes,function(arg){return arg.name.value}),i=0;i<argDefs.length;i++){var argDef=argDefs[i],name=argDef.name,argType=argDef.type,argumentNode=argNodeMap[name],defaultValue=argDef.defaultValue;if(argumentNode)if(argumentNode.value.kind===Kind.VARIABLE){var variableName=argumentNode.value.name.value;if(variableValues&&!(0,_isInvalid2.default)(variableValues[variableName]))coercedValues[name]=variableValues[variableName];else if((0,_isInvalid2.default)(defaultValue)){if(argType instanceof _definition.GraphQLNonNull)throw new _error.GraphQLError('Argument "'+name+'" of required type "'+String(argType)+'" was provided the variable "$'+variableName+'" which was not provided a runtime value.',[argumentNode.value])}else coercedValues[name]=defaultValue}else{var valueNode=argumentNode.value,coercedValue=(0,_valueFromAST.valueFromAST)(valueNode,argType,variableValues);if((0,_isInvalid2.default)(coercedValue)){var errors=(0,_isValidLiteralValue.isValidLiteralValue)(argType,valueNode),message=errors?"\n"+errors.join("\n"):"";throw new _error.GraphQLError('Argument "'+name+'" got invalid value '+(0,_printer.print)(valueNode)+"."+message,[argumentNode.value])}coercedValues[name]=coercedValue}else if((0,_isInvalid2.default)(defaultValue)){if(argType instanceof _definition.GraphQLNonNull)throw new _error.GraphQLError('Argument "'+name+'" of required type "'+String(argType)+'" was not provided.',[node])}else coercedValues[name]=defaultValue}return coercedValues}function coerceValue(type,value){var _value=value;if(!(0,_isInvalid2.default)(_value)){if(type instanceof _definition.GraphQLNonNull){if(null===_value)return;return coerceValue(type.ofType,_value)}if(null===_value)return null;if(type instanceof _definition.GraphQLList){var itemType=type.ofType;if((0,_iterall.isCollection)(_value)){var coercedValues=[],valueIter=(0,_iterall.createIterator)(_value);if(!valueIter)return;for(var step=void 0;!(step=valueIter.next()).done;){var itemValue=coerceValue(itemType,step.value);if((0,_isInvalid2.default)(itemValue))return;coercedValues.push(itemValue)}return coercedValues}var coercedValue=coerceValue(itemType,_value);if((0,_isInvalid2.default)(coercedValue))return;return[coerceValue(itemType,_value)]}if(type instanceof _definition.GraphQLInputObjectType){if("object"!=typeof _value)return;for(var coercedObj=Object.create(null),fields=type.getFields(),fieldNames=Object.keys(fields),i=0;i<fieldNames.length;i++){var fieldName=fieldNames[i],field=fields[fieldName];if((0,_isInvalid2.default)(_value[fieldName]))if((0,_isInvalid2.default)(field.defaultValue)){if(field.type instanceof _definition.GraphQLNonNull)return}else coercedObj[fieldName]=field.defaultValue;else{var fieldValue=coerceValue(field.type,_value[fieldName]);if((0,_isInvalid2.default)(fieldValue))return;coercedObj[fieldName]=fieldValue}}return coercedObj}(0,_invariant2.default)(type instanceof _definition.GraphQLScalarType||type instanceof _definition.GraphQLEnumType,"Must be input type");var parsed=type.parseValue(_value);if(!(0,_isNullish2.default)(parsed))return parsed}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getVariableValues=function(schema,varDefNodes,inputs){for(var coercedValues=Object.create(null),i=0;i<varDefNodes.length;i++){var varDefNode=varDefNodes[i],varName=varDefNode.variable.name.value,varType=(0,_typeFromAST.typeFromAST)(schema,varDefNode.type);if(!(0,_definition.isInputType)(varType))throw new _error.GraphQLError('Variable "$'+varName+'" expected value of type "'+(0,_printer.print)(varDefNode.type)+'" which cannot be used as an input type.',[varDefNode.type]);var value=inputs[varName];if((0,_isInvalid2.default)(value)){var defaultValue=varDefNode.defaultValue;if(defaultValue&&(coercedValues[varName]=(0,_valueFromAST.valueFromAST)(defaultValue,varType)),varType instanceof _definition.GraphQLNonNull)throw new _error.GraphQLError('Variable "$'+varName+'" of required type "'+String(varType)+'" was not provided.',[varDefNode])}else{var errors=(0,_isValidJSValue.isValidJSValue)(value,varType);if(errors.length){var message=errors?"\n"+errors.join("\n"):"";throw new _error.GraphQLError('Variable "$'+varName+'" got invalid value '+JSON.stringify(value)+"."+message,[varDefNode])}var coercedValue=coerceValue(varType,value);(0,_invariant2.default)(!(0,_isInvalid2.default)(coercedValue),"Should have reported error."),coercedValues[varName]=coercedValue}}return coercedValues},exports.getArgumentValues=getArgumentValues,exports.getDirectiveValues=function(directiveDef,node,variableValues){var directiveNode=node.directives&&(0,_find2.default)(node.directives,function(directive){return directive.name.value===directiveDef.name});if(directiveNode)return getArgumentValues(directiveDef,directiveNode,variableValues)};var _iterall=require("iterall"),_error=require("../error"),_find2=_interopRequireDefault(require("../jsutils/find")),_invariant2=_interopRequireDefault(require("../jsutils/invariant")),_isNullish2=_interopRequireDefault(require("../jsutils/isNullish")),_isInvalid2=_interopRequireDefault(require("../jsutils/isInvalid")),_keyMap2=_interopRequireDefault(require("../jsutils/keyMap")),_typeFromAST=require("../utilities/typeFromAST"),_valueFromAST=require("../utilities/valueFromAST"),_isValidJSValue=require("../utilities/isValidJSValue"),_isValidLiteralValue=require("../utilities/isValidLiteralValue"),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_printer=require("../language/printer"),_definition=require("../type/definition")},{"../error":85,"../jsutils/find":93,"../jsutils/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../jsutils/keyMap":97,"../language/kinds":102,"../language/printer":106,"../type/definition":112,"../utilities/isValidJSValue":130,"../utilities/isValidLiteralValue":131,"../utilities/typeFromAST":135,"../utilities/valueFromAST":136,iterall:166}],91:[function(require,module,exports){"use strict";function graphqlImpl(schema,source,rootValue,contextValue,variableValues,operationName,fieldResolver){return new Promise(function(resolve){var document=void 0;try{document=(0,_parser.parse)(source)}catch(syntaxError){return resolve({errors:[syntaxError]})}var validationErrors=(0,_validate.validate)(schema,document);if(validationErrors.length>0)return resolve({errors:validationErrors});resolve((0,_execute.execute)(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver))})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.graphql=function(argsOrSchema,source,rootValue,contextValue,variableValues,operationName,fieldResolver){var args=1===arguments.length?argsOrSchema:void 0,schema=args?args.schema:argsOrSchema;return args?graphqlImpl(schema,args.source,args.rootValue,args.contextValue,args.variableValues,args.operationName,args.fieldResolver):graphqlImpl(schema,source,rootValue,contextValue,variableValues,operationName,fieldResolver)};var _parser=require("./language/parser"),_validate=require("./validation/validate"),_execute=require("./execution/execute")},{"./execution/execute":88,"./language/parser":105,"./validation/validate":165}],92:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _graphql=require("./graphql");Object.defineProperty(exports,"graphql",{enumerable:!0,get:function(){return _graphql.graphql}});var _type=require("./type");Object.defineProperty(exports,"GraphQLSchema",{enumerable:!0,get:function(){return _type.GraphQLSchema}}),Object.defineProperty(exports,"GraphQLScalarType",{enumerable:!0,get:function(){return _type.GraphQLScalarType}}),Object.defineProperty(exports,"GraphQLObjectType",{enumerable:!0,get:function(){return _type.GraphQLObjectType}}),Object.defineProperty(exports,"GraphQLInterfaceType",{enumerable:!0,get:function(){return _type.GraphQLInterfaceType}}),Object.defineProperty(exports,"GraphQLUnionType",{enumerable:!0,get:function(){return _type.GraphQLUnionType}}),Object.defineProperty(exports,"GraphQLEnumType",{enumerable:!0,get:function(){return _type.GraphQLEnumType}}),Object.defineProperty(exports,"GraphQLInputObjectType",{enumerable:!0,get:function(){return _type.GraphQLInputObjectType}}),Object.defineProperty(exports,"GraphQLList",{enumerable:!0,get:function(){return _type.GraphQLList}}),Object.defineProperty(exports,"GraphQLNonNull",{enumerable:!0,get:function(){return _type.GraphQLNonNull}}),Object.defineProperty(exports,"GraphQLDirective",{enumerable:!0,get:function(){return _type.GraphQLDirective}}),Object.defineProperty(exports,"TypeKind",{enumerable:!0,get:function(){return _type.TypeKind}}),Object.defineProperty(exports,"DirectiveLocation",{enumerable:!0,get:function(){return _type.DirectiveLocation}}),Object.defineProperty(exports,"GraphQLInt",{enumerable:!0,get:function(){return _type.GraphQLInt}}),Object.defineProperty(exports,"GraphQLFloat",{enumerable:!0,get:function(){return _type.GraphQLFloat}}),Object.defineProperty(exports,"GraphQLString",{enumerable:!0,get:function(){return _type.GraphQLString}}),Object.defineProperty(exports,"GraphQLBoolean",{enumerable:!0,get:function(){return _type.GraphQLBoolean}}),Object.defineProperty(exports,"GraphQLID",{enumerable:!0,get:function(){return _type.GraphQLID}}),Object.defineProperty(exports,"specifiedDirectives",{enumerable:!0,get:function(){return _type.specifiedDirectives}}),Object.defineProperty(exports,"GraphQLIncludeDirective",{enumerable:!0,get:function(){return _type.GraphQLIncludeDirective}}),Object.defineProperty(exports,"GraphQLSkipDirective",{enumerable:!0,get:function(){return _type.GraphQLSkipDirective}}),Object.defineProperty(exports,"GraphQLDeprecatedDirective",{enumerable:!0,get:function(){return _type.GraphQLDeprecatedDirective}}),Object.defineProperty(exports,"DEFAULT_DEPRECATION_REASON",{enumerable:!0,get:function(){return _type.DEFAULT_DEPRECATION_REASON}}),Object.defineProperty(exports,"SchemaMetaFieldDef",{enumerable:!0,get:function(){return _type.SchemaMetaFieldDef}}),Object.defineProperty(exports,"TypeMetaFieldDef",{enumerable:!0,get:function(){return _type.TypeMetaFieldDef}}),Object.defineProperty(exports,"TypeNameMetaFieldDef",{enumerable:!0,get:function(){return _type.TypeNameMetaFieldDef}}),Object.defineProperty(exports,"__Schema",{enumerable:!0,get:function(){return _type.__Schema}}),Object.defineProperty(exports,"__Directive",{enumerable:!0,get:function(){return _type.__Directive}}),Object.defineProperty(exports,"__DirectiveLocation",{enumerable:!0,get:function(){return _type.__DirectiveLocation}}),Object.defineProperty(exports,"__Type",{enumerable:!0,get:function(){return _type.__Type}}),Object.defineProperty(exports,"__Field",{enumerable:!0,get:function(){return _type.__Field}}),Object.defineProperty(exports,"__InputValue",{enumerable:!0,get:function(){return _type.__InputValue}}),Object.defineProperty(exports,"__EnumValue",{enumerable:!0,get:function(){return _type.__EnumValue}}),Object.defineProperty(exports,"__TypeKind",{enumerable:!0,get:function(){return _type.__TypeKind}}),Object.defineProperty(exports,"isType",{enumerable:!0,get:function(){return _type.isType}}),Object.defineProperty(exports,"isInputType",{enumerable:!0,get:function(){return _type.isInputType}}),Object.defineProperty(exports,"isOutputType",{enumerable:!0,get:function(){return _type.isOutputType}}),Object.defineProperty(exports,"isLeafType",{enumerable:!0,get:function(){return _type.isLeafType}}),Object.defineProperty(exports,"isCompositeType",{enumerable:!0,get:function(){return _type.isCompositeType}}),Object.defineProperty(exports,"isAbstractType",{enumerable:!0,get:function(){return _type.isAbstractType}}),Object.defineProperty(exports,"isNamedType",{enumerable:!0,get:function(){return _type.isNamedType}}),Object.defineProperty(exports,"assertType",{enumerable:!0,get:function(){return _type.assertType}}),Object.defineProperty(exports,"assertInputType",{enumerable:!0,get:function(){return _type.assertInputType}}),Object.defineProperty(exports,"assertOutputType",{enumerable:!0,get:function(){return _type.assertOutputType}}),Object.defineProperty(exports,"assertLeafType",{enumerable:!0,get:function(){return _type.assertLeafType}}),Object.defineProperty(exports,"assertCompositeType",{enumerable:!0,get:function(){return _type.assertCompositeType}}),Object.defineProperty(exports,"assertAbstractType",{enumerable:!0,get:function(){return _type.assertAbstractType}}),Object.defineProperty(exports,"assertNamedType",{enumerable:!0,get:function(){return _type.assertNamedType}}),Object.defineProperty(exports,"getNullableType",{enumerable:!0,get:function(){return _type.getNullableType}}),Object.defineProperty(exports,"getNamedType",{enumerable:!0,get:function(){return _type.getNamedType}});var _language=require("./language");Object.defineProperty(exports,"Source",{enumerable:!0,get:function(){return _language.Source}}),Object.defineProperty(exports,"getLocation",{enumerable:!0,get:function(){return _language.getLocation}}),Object.defineProperty(exports,"parse",{enumerable:!0,get:function(){return _language.parse}}),Object.defineProperty(exports,"parseValue",{enumerable:!0,get:function(){return _language.parseValue}}),Object.defineProperty(exports,"parseType",{enumerable:!0,get:function(){return _language.parseType}}),Object.defineProperty(exports,"print",{enumerable:!0,get:function(){return _language.print}}),Object.defineProperty(exports,"visit",{enumerable:!0,get:function(){return _language.visit}}),Object.defineProperty(exports,"visitInParallel",{enumerable:!0,get:function(){return _language.visitInParallel}}),Object.defineProperty(exports,"visitWithTypeInfo",{enumerable:!0,get:function(){return _language.visitWithTypeInfo}}),Object.defineProperty(exports,"getVisitFn",{enumerable:!0,get:function(){return _language.getVisitFn}}),Object.defineProperty(exports,"Kind",{enumerable:!0,get:function(){return _language.Kind}}),Object.defineProperty(exports,"TokenKind",{enumerable:!0,get:function(){return _language.TokenKind}}),Object.defineProperty(exports,"BREAK",{enumerable:!0,get:function(){return _language.BREAK}});var _execution=require("./execution");Object.defineProperty(exports,"execute",{enumerable:!0,get:function(){return _execution.execute}}),Object.defineProperty(exports,"defaultFieldResolver",{enumerable:!0,get:function(){return _execution.defaultFieldResolver}}),Object.defineProperty(exports,"responsePathAsArray",{enumerable:!0,get:function(){return _execution.responsePathAsArray}}),Object.defineProperty(exports,"getDirectiveValues",{enumerable:!0,get:function(){return _execution.getDirectiveValues}});var _subscription=require("./subscription");Object.defineProperty(exports,"subscribe",{enumerable:!0,get:function(){return _subscription.subscribe}}),Object.defineProperty(exports,"createSourceEventStream",{enumerable:!0,get:function(){return _subscription.createSourceEventStream}});var _validation=require("./validation");Object.defineProperty(exports,"validate",{enumerable:!0,get:function(){return _validation.validate}}),Object.defineProperty(exports,"ValidationContext",{enumerable:!0,get:function(){return _validation.ValidationContext}}),Object.defineProperty(exports,"specifiedRules",{enumerable:!0,get:function(){return _validation.specifiedRules}}),Object.defineProperty(exports,"ArgumentsOfCorrectTypeRule",{enumerable:!0,get:function(){return _validation.ArgumentsOfCorrectTypeRule}}),Object.defineProperty(exports,"DefaultValuesOfCorrectTypeRule",{enumerable:!0,get:function(){return _validation.DefaultValuesOfCorrectTypeRule}}),Object.defineProperty(exports,"FieldsOnCorrectTypeRule",{enumerable:!0,get:function(){return _validation.FieldsOnCorrectTypeRule}}),Object.defineProperty(exports,"FragmentsOnCompositeTypesRule",{enumerable:!0,get:function(){return _validation.FragmentsOnCompositeTypesRule}}),Object.defineProperty(exports,"KnownArgumentNamesRule",{enumerable:!0,get:function(){return _validation.KnownArgumentNamesRule}}),Object.defineProperty(exports,"KnownDirectivesRule",{enumerable:!0,get:function(){return _validation.KnownDirectivesRule}}),Object.defineProperty(exports,"KnownFragmentNamesRule",{enumerable:!0,get:function(){return _validation.KnownFragmentNamesRule}}),Object.defineProperty(exports,"KnownTypeNamesRule",{enumerable:!0,get:function(){return _validation.KnownTypeNamesRule}}),Object.defineProperty(exports,"LoneAnonymousOperationRule",{enumerable:!0,get:function(){return _validation.LoneAnonymousOperationRule}}),Object.defineProperty(exports,"NoFragmentCyclesRule",{enumerable:!0,get:function(){return _validation.NoFragmentCyclesRule}}),Object.defineProperty(exports,"NoUndefinedVariablesRule",{enumerable:!0,get:function(){return _validation.NoUndefinedVariablesRule}}),Object.defineProperty(exports,"NoUnusedFragmentsRule",{enumerable:!0,get:function(){return _validation.NoUnusedFragmentsRule}}),Object.defineProperty(exports,"NoUnusedVariablesRule",{enumerable:!0,get:function(){return _validation.NoUnusedVariablesRule}}),Object.defineProperty(exports,"OverlappingFieldsCanBeMergedRule",{enumerable:!0,get:function(){return _validation.OverlappingFieldsCanBeMergedRule}}),Object.defineProperty(exports,"PossibleFragmentSpreadsRule",{enumerable:!0,get:function(){return _validation.PossibleFragmentSpreadsRule}}),Object.defineProperty(exports,"ProvidedNonNullArgumentsRule",{enumerable:!0,get:function(){return _validation.ProvidedNonNullArgumentsRule}}),Object.defineProperty(exports,"ScalarLeafsRule",{enumerable:!0,get:function(){return _validation.ScalarLeafsRule}}),Object.defineProperty(exports,"SingleFieldSubscriptionsRule",{enumerable:!0,get:function(){return _validation.SingleFieldSubscriptionsRule}}),Object.defineProperty(exports,"UniqueArgumentNamesRule",{enumerable:!0,get:function(){return _validation.UniqueArgumentNamesRule}}),Object.defineProperty(exports,"UniqueDirectivesPerLocationRule",{enumerable:!0,get:function(){return _validation.UniqueDirectivesPerLocationRule}}),Object.defineProperty(exports,"UniqueFragmentNamesRule",{enumerable:!0,get:function(){return _validation.UniqueFragmentNamesRule}}),Object.defineProperty(exports,"UniqueInputFieldNamesRule",{enumerable:!0,get:function(){return _validation.UniqueInputFieldNamesRule}}),Object.defineProperty(exports,"UniqueOperationNamesRule",{enumerable:!0,get:function(){return _validation.UniqueOperationNamesRule}}),Object.defineProperty(exports,"UniqueVariableNamesRule",{enumerable:!0,get:function(){return _validation.UniqueVariableNamesRule}}),Object.defineProperty(exports,"VariablesAreInputTypesRule",{enumerable:!0,get:function(){return _validation.VariablesAreInputTypesRule}}),Object.defineProperty(exports,"VariablesInAllowedPositionRule",{enumerable:!0,get:function(){return _validation.VariablesInAllowedPositionRule}});var _error=require("./error");Object.defineProperty(exports,"GraphQLError",{enumerable:!0,get:function(){return _error.GraphQLError}}),Object.defineProperty(exports,"formatError",{enumerable:!0,get:function(){return _error.formatError}});var _utilities=require("./utilities");Object.defineProperty(exports,"introspectionQuery",{enumerable:!0,get:function(){return _utilities.introspectionQuery}}),Object.defineProperty(exports,"getOperationAST",{enumerable:!0,get:function(){return _utilities.getOperationAST}}),Object.defineProperty(exports,"buildClientSchema",{enumerable:!0,get:function(){return _utilities.buildClientSchema}}),Object.defineProperty(exports,"buildASTSchema",{enumerable:!0,get:function(){return _utilities.buildASTSchema}}),Object.defineProperty(exports,"buildSchema",{enumerable:!0,get:function(){return _utilities.buildSchema}}),Object.defineProperty(exports,"extendSchema",{enumerable:!0,get:function(){return _utilities.extendSchema}}),Object.defineProperty(exports,"printSchema",{enumerable:!0,get:function(){return _utilities.printSchema}}),Object.defineProperty(exports,"printIntrospectionSchema",{enumerable:!0,get:function(){return _utilities.printIntrospectionSchema}}),Object.defineProperty(exports,"printType",{enumerable:!0,get:function(){return _utilities.printType}}),Object.defineProperty(exports,"typeFromAST",{enumerable:!0,get:function(){return _utilities.typeFromAST}}),Object.defineProperty(exports,"valueFromAST",{enumerable:!0,get:function(){return _utilities.valueFromAST}}),Object.defineProperty(exports,"astFromValue",{enumerable:!0,get:function(){return _utilities.astFromValue}}),Object.defineProperty(exports,"TypeInfo",{enumerable:!0,get:function(){return _utilities.TypeInfo}}),Object.defineProperty(exports,"isValidJSValue",{enumerable:!0,get:function(){return _utilities.isValidJSValue}}),Object.defineProperty(exports,"isValidLiteralValue",{enumerable:!0,get:function(){return _utilities.isValidLiteralValue}}),Object.defineProperty(exports,"concatAST",{enumerable:!0,get:function(){return _utilities.concatAST}}),Object.defineProperty(exports,"separateOperations",{enumerable:!0,get:function(){return _utilities.separateOperations}}),Object.defineProperty(exports,"isEqualType",{enumerable:!0,get:function(){return _utilities.isEqualType}}),Object.defineProperty(exports,"isTypeSubTypeOf",{enumerable:!0,get:function(){return _utilities.isTypeSubTypeOf}}),Object.defineProperty(exports,"doTypesOverlap",{enumerable:!0,get:function(){return _utilities.doTypesOverlap}}),Object.defineProperty(exports,"assertValidName",{enumerable:!0,get:function(){return _utilities.assertValidName}}),Object.defineProperty(exports,"findBreakingChanges",{enumerable:!0,get:function(){return _utilities.findBreakingChanges}}),Object.defineProperty(exports,"BreakingChangeType",{enumerable:!0,get:function(){return _utilities.BreakingChangeType}}),Object.defineProperty(exports,"DangerousChangeType",{enumerable:!0,get:function(){return _utilities.DangerousChangeType}}),Object.defineProperty(exports,"findDeprecatedUsages",{enumerable:!0,get:function(){return _utilities.findDeprecatedUsages}})},{"./error":85,"./execution":89,"./graphql":91,"./language":101,"./subscription":109,"./type":114,"./utilities":128,"./validation":137}],93:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(list,predicate){for(var i=0;i<list.length;i++)if(predicate(list[i]))return list[i]}},{}],94:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(condition,message){if(!condition)throw new Error(message)}},{}],95:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(value){return void 0===value||value!==value}},{}],96:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(value){return null===value||void 0===value||value!==value}},{}],97:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(list,keyFn){return list.reduce(function(map,item){return map[keyFn(item)]=item,map},Object.create(null))}},{}],98:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(list,keyFn,valFn){return list.reduce(function(map,item){return map[keyFn(item)]=valFn(item),map},Object.create(null))}},{}],99:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(items){var selected=items.slice(0,MAX_LENGTH);return selected.map(function(item){return'"'+item+'"'}).reduce(function(list,quoted,index){return list+(selected.length>2?", ":" ")+(index===selected.length-1?"or ":"")+quoted})};var MAX_LENGTH=5},{}],100:[function(require,module,exports){"use strict";function lexicalDistance(a,b){var i=void 0,j=void 0,d=[],aLength=a.length,bLength=b.length;for(i=0;i<=aLength;i++)d[i]=[i];for(j=1;j<=bLength;j++)d[0][j]=j;for(i=1;i<=aLength;i++)for(j=1;j<=bLength;j++){var cost=a[i-1]===b[j-1]?0:1;d[i][j]=Math.min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+cost),i>1&&j>1&&a[i-1]===b[j-2]&&a[i-2]===b[j-1]&&(d[i][j]=Math.min(d[i][j],d[i-2][j-2]+cost))}return d[aLength][bLength]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(input,options){for(var optionsByDistance=Object.create(null),oLength=options.length,inputThreshold=input.length/2,i=0;i<oLength;i++){var distance=lexicalDistance(input,options[i]);distance<=Math.max(inputThreshold,options[i].length/2,1)&&(optionsByDistance[options[i]]=distance)}return Object.keys(optionsByDistance).sort(function(a,b){return optionsByDistance[a]-optionsByDistance[b]})}},{}],101:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BREAK=exports.getVisitFn=exports.visitWithTypeInfo=exports.visitInParallel=exports.visit=exports.Source=exports.print=exports.parseType=exports.parseValue=exports.parse=exports.TokenKind=exports.createLexer=exports.Kind=exports.getLocation=void 0;var _location=require("./location");Object.defineProperty(exports,"getLocation",{enumerable:!0,get:function(){return _location.getLocation}});var _lexer=require("./lexer");Object.defineProperty(exports,"createLexer",{enumerable:!0,get:function(){return _lexer.createLexer}}),Object.defineProperty(exports,"TokenKind",{enumerable:!0,get:function(){return _lexer.TokenKind}});var _parser=require("./parser");Object.defineProperty(exports,"parse",{enumerable:!0,get:function(){return _parser.parse}}),Object.defineProperty(exports,"parseValue",{enumerable:!0,get:function(){return _parser.parseValue}}),Object.defineProperty(exports,"parseType",{enumerable:!0,get:function(){return _parser.parseType}});var _printer=require("./printer");Object.defineProperty(exports,"print",{enumerable:!0,get:function(){return _printer.print}});var _source=require("./source");Object.defineProperty(exports,"Source",{enumerable:!0,get:function(){return _source.Source}});var _visitor=require("./visitor");Object.defineProperty(exports,"visit",{enumerable:!0,get:function(){return _visitor.visit}}),Object.defineProperty(exports,"visitInParallel",{enumerable:!0,get:function(){return _visitor.visitInParallel}}),Object.defineProperty(exports,"visitWithTypeInfo",{enumerable:!0,get:function(){return _visitor.visitWithTypeInfo}}),Object.defineProperty(exports,"getVisitFn",{enumerable:!0,get:function(){return _visitor.getVisitFn}}),Object.defineProperty(exports,"BREAK",{enumerable:!0,get:function(){return _visitor.BREAK}});var Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("./kinds"));exports.Kind=Kind},{"./kinds":102,"./lexer":103,"./location":104,"./parser":105,"./printer":106,"./source":107,"./visitor":108}],102:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.NAME="Name",exports.DOCUMENT="Document",exports.OPERATION_DEFINITION="OperationDefinition",exports.VARIABLE_DEFINITION="VariableDefinition",exports.VARIABLE="Variable",exports.SELECTION_SET="SelectionSet",exports.FIELD="Field",exports.ARGUMENT="Argument",exports.FRAGMENT_SPREAD="FragmentSpread",exports.INLINE_FRAGMENT="InlineFragment",exports.FRAGMENT_DEFINITION="FragmentDefinition",exports.INT="IntValue",exports.FLOAT="FloatValue",exports.STRING="StringValue",exports.BOOLEAN="BooleanValue",exports.NULL="NullValue",exports.ENUM="EnumValue",exports.LIST="ListValue",exports.OBJECT="ObjectValue",exports.OBJECT_FIELD="ObjectField",exports.DIRECTIVE="Directive",exports.NAMED_TYPE="NamedType",exports.LIST_TYPE="ListType",exports.NON_NULL_TYPE="NonNullType",exports.SCHEMA_DEFINITION="SchemaDefinition",exports.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",exports.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",exports.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",exports.FIELD_DEFINITION="FieldDefinition",exports.INPUT_VALUE_DEFINITION="InputValueDefinition",exports.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",exports.UNION_TYPE_DEFINITION="UnionTypeDefinition",exports.ENUM_TYPE_DEFINITION="EnumTypeDefinition",exports.ENUM_VALUE_DEFINITION="EnumValueDefinition",exports.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",exports.TYPE_EXTENSION_DEFINITION="TypeExtensionDefinition",exports.DIRECTIVE_DEFINITION="DirectiveDefinition"},{}],103:[function(require,module,exports){"use strict";function advanceLexer(){var token=this.lastToken=this.token;if(token.kind!==EOF){do{token=token.next=readToken(this,token)}while(token.kind===COMMENT);this.token=token}return token}function Tok(kind,start,end,line,column,prev,value){this.kind=kind,this.start=start,this.end=end,this.line=line,this.column=column,this.value=value,this.prev=prev,this.next=null}function printCharCode(code){return isNaN(code)?EOF:code<127?JSON.stringify(String.fromCharCode(code)):'"\\u'+("00"+code.toString(16).toUpperCase()).slice(-4)+'"'}function readToken(lexer,prev){var source=lexer.source,body=source.body,bodyLength=body.length,position=positionAfterWhitespace(body,prev.end,lexer),line=lexer.line,col=1+position-lexer.lineStart;if(position>=bodyLength)return new Tok(EOF,bodyLength,bodyLength,line,col,prev);var code=charCodeAt.call(body,position);if(code<32&&9!==code&&10!==code&&13!==code)throw(0,_error.syntaxError)(source,position,"Cannot contain the invalid character "+printCharCode(code)+".");switch(code){case 33:return new Tok(BANG,position,position+1,line,col,prev);case 35:return readComment(source,position,line,col,prev);case 36:return new Tok(DOLLAR,position,position+1,line,col,prev);case 40:return new Tok(PAREN_L,position,position+1,line,col,prev);case 41:return new Tok(PAREN_R,position,position+1,line,col,prev);case 46:if(46===charCodeAt.call(body,position+1)&&46===charCodeAt.call(body,position+2))return new Tok(SPREAD,position,position+3,line,col,prev);break;case 58:return new Tok(COLON,position,position+1,line,col,prev);case 61:return new Tok(EQUALS,position,position+1,line,col,prev);case 64:return new Tok(AT,position,position+1,line,col,prev);case 91:return new Tok(BRACKET_L,position,position+1,line,col,prev);case 93:return new Tok(BRACKET_R,position,position+1,line,col,prev);case 123:return new Tok(BRACE_L,position,position+1,line,col,prev);case 124:return new Tok(PIPE,position,position+1,line,col,prev);case 125:return new Tok(BRACE_R,position,position+1,line,col,prev);case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 95:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:return readName(source,position,line,col,prev);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(source,position,code,line,col,prev);case 34:return readString(source,position,line,col,prev)}throw(0,_error.syntaxError)(source,position,unexpectedCharacterMessage(code))}function unexpectedCharacterMessage(code){return 39===code?"Unexpected single quote character ('), did you mean to use a double quote (\")?":"Cannot parse the unexpected character "+printCharCode(code)+"."}function positionAfterWhitespace(body,startPosition,lexer){for(var bodyLength=body.length,position=startPosition;position<bodyLength;){var code=charCodeAt.call(body,position);if(9===code||32===code||44===code||65279===code)++position;else if(10===code)++position,++lexer.line,lexer.lineStart=position;else{if(13!==code)break;10===charCodeAt.call(body,position+1)?position+=2:++position,++lexer.line,lexer.lineStart=position}}return position}function readComment(source,start,line,col,prev){var body=source.body,code=void 0,position=start;do{code=charCodeAt.call(body,++position)}while(null!==code&&(code>31||9===code));return new Tok(COMMENT,start,position,line,col,prev,slice.call(body,start+1,position))}function readNumber(source,start,firstCode,line,col,prev){var body=source.body,code=firstCode,position=start,isFloat=!1;if(45===code&&(code=charCodeAt.call(body,++position)),48===code){if((code=charCodeAt.call(body,++position))>=48&&code<=57)throw(0,_error.syntaxError)(source,position,"Invalid number, unexpected digit after 0: "+printCharCode(code)+".")}else position=readDigits(source,position,code),code=charCodeAt.call(body,position);return 46===code&&(isFloat=!0,code=charCodeAt.call(body,++position),position=readDigits(source,position,code),code=charCodeAt.call(body,position)),69!==code&&101!==code||(isFloat=!0,43!==(code=charCodeAt.call(body,++position))&&45!==code||(code=charCodeAt.call(body,++position)),position=readDigits(source,position,code)),new Tok(isFloat?FLOAT:INT,start,position,line,col,prev,slice.call(body,start,position))}function readDigits(source,start,firstCode){var body=source.body,position=start,code=firstCode;if(code>=48&&code<=57){do{code=charCodeAt.call(body,++position)}while(code>=48&&code<=57);return position}throw(0,_error.syntaxError)(source,position,"Invalid number, expected digit but got: "+printCharCode(code)+".")}function readString(source,start,line,col,prev){for(var body=source.body,position=start+1,chunkStart=position,code=0,value="";position<body.length&&null!==(code=charCodeAt.call(body,position))&&10!==code&&13!==code&&34!==code;){if(code<32&&9!==code)throw(0,_error.syntaxError)(source,position,"Invalid character within String: "+printCharCode(code)+".");if(++position,92===code){switch(value+=slice.call(body,chunkStart,position-1),code=charCodeAt.call(body,position)){case 34:value+='"';break;case 47:value+="/";break;case 92:value+="\\";break;case 98:value+="\b";break;case 102:value+="\f";break;case 110:value+="\n";break;case 114:value+="\r";break;case 116:value+="\t";break;case 117:var charCode=uniCharCode(charCodeAt.call(body,position+1),charCodeAt.call(body,position+2),charCodeAt.call(body,position+3),charCodeAt.call(body,position+4));if(charCode<0)throw(0,_error.syntaxError)(source,position,"Invalid character escape sequence: \\u"+body.slice(position+1,position+5)+".");value+=String.fromCharCode(charCode),position+=4;break;default:throw(0,_error.syntaxError)(source,position,"Invalid character escape sequence: \\"+String.fromCharCode(code)+".")}chunkStart=++position}}if(34!==code)throw(0,_error.syntaxError)(source,position,"Unterminated string.");return value+=slice.call(body,chunkStart,position),new Tok(STRING,start,position+1,line,col,prev,value)}function uniCharCode(a,b,c,d){return char2hex(a)<<12|char2hex(b)<<8|char2hex(c)<<4|char2hex(d)}function char2hex(a){return a>=48&&a<=57?a-48:a>=65&&a<=70?a-55:a>=97&&a<=102?a-87:-1}function readName(source,position,line,col,prev){for(var body=source.body,bodyLength=body.length,end=position+1,code=0;end!==bodyLength&&null!==(code=charCodeAt.call(body,end))&&(95===code||code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122);)++end;return new Tok(NAME,position,end,line,col,prev,slice.call(body,position,end))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.TokenKind=void 0,exports.createLexer=function(source,options){var startOfFileToken=new Tok(SOF,0,0,0,0,null);return{source:source,options:options,lastToken:startOfFileToken,token:startOfFileToken,line:1,lineStart:0,advance:advanceLexer}},exports.getTokenDesc=function(token){var value=token.value;return value?token.kind+' "'+value+'"':token.kind};var _error=require("../error"),SOF="<SOF>",EOF="<EOF>",BANG="!",DOLLAR="$",PAREN_L="(",PAREN_R=")",SPREAD="...",COLON=":",EQUALS="=",AT="@",BRACKET_L="[",BRACKET_R="]",BRACE_L="{",PIPE="|",BRACE_R="}",NAME="Name",INT="Int",FLOAT="Float",STRING="String",COMMENT="Comment",charCodeAt=(exports.TokenKind={SOF:SOF,EOF:EOF,BANG:BANG,DOLLAR:DOLLAR,PAREN_L:PAREN_L,PAREN_R:PAREN_R,SPREAD:SPREAD,COLON:COLON,EQUALS:EQUALS,AT:AT,BRACKET_L:BRACKET_L,BRACKET_R:BRACKET_R,BRACE_L:BRACE_L,PIPE:PIPE,BRACE_R:BRACE_R,NAME:NAME,INT:INT,FLOAT:FLOAT,STRING:STRING,COMMENT:COMMENT},String.prototype.charCodeAt),slice=String.prototype.slice;Tok.prototype.toJSON=Tok.prototype.inspect=function(){return{kind:this.kind,value:this.value,line:this.line,column:this.column}}},{"../error":85}],104:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getLocation=function(source,position){for(var lineRegexp=/\r\n|[\n\r]/g,line=1,column=position+1,match=void 0;(match=lineRegexp.exec(source.body))&&match.index<position;)line+=1,column=position+1-(match.index+match[0].length);return{line:line,column:column}}},{}],105:[function(require,module,exports){"use strict";function parseName(lexer){var token=expect(lexer,_lexer.TokenKind.NAME);return{kind:_kinds.NAME,value:token.value,loc:loc(lexer,token)}}function parseDocument(lexer){var start=lexer.token;expect(lexer,_lexer.TokenKind.SOF);var definitions=[];do{definitions.push(parseDefinition(lexer))}while(!skip(lexer,_lexer.TokenKind.EOF));return{kind:_kinds.DOCUMENT,definitions:definitions,loc:loc(lexer,start)}}function parseDefinition(lexer){if(peek(lexer,_lexer.TokenKind.BRACE_L))return parseOperationDefinition(lexer);if(peek(lexer,_lexer.TokenKind.NAME))switch(lexer.token.value){case"query":case"mutation":case"subscription":return parseOperationDefinition(lexer);case"fragment":return parseFragmentDefinition(lexer);case"schema":case"scalar":case"type":case"interface":case"union":case"enum":case"input":case"extend":case"directive":return parseTypeSystemDefinition(lexer)}throw unexpected(lexer)}function parseOperationDefinition(lexer){var start=lexer.token;if(peek(lexer,_lexer.TokenKind.BRACE_L))return{kind:_kinds.OPERATION_DEFINITION,operation:"query",name:null,variableDefinitions:null,directives:[],selectionSet:parseSelectionSet(lexer),loc:loc(lexer,start)};var operation=parseOperationType(lexer),name=void 0;return peek(lexer,_lexer.TokenKind.NAME)&&(name=parseName(lexer)),{kind:_kinds.OPERATION_DEFINITION,operation:operation,name:name,variableDefinitions:parseVariableDefinitions(lexer),directives:parseDirectives(lexer),selectionSet:parseSelectionSet(lexer),loc:loc(lexer,start)}}function parseOperationType(lexer){var operationToken=expect(lexer,_lexer.TokenKind.NAME);switch(operationToken.value){case"query":return"query";case"mutation":return"mutation";case"subscription":return"subscription"}throw unexpected(lexer,operationToken)}function parseVariableDefinitions(lexer){return peek(lexer,_lexer.TokenKind.PAREN_L)?many(lexer,_lexer.TokenKind.PAREN_L,parseVariableDefinition,_lexer.TokenKind.PAREN_R):[]}function parseVariableDefinition(lexer){var start=lexer.token;return{kind:_kinds.VARIABLE_DEFINITION,variable:parseVariable(lexer),type:(expect(lexer,_lexer.TokenKind.COLON),parseTypeReference(lexer)),defaultValue:skip(lexer,_lexer.TokenKind.EQUALS)?parseValueLiteral(lexer,!0):null,loc:loc(lexer,start)}}function parseVariable(lexer){var start=lexer.token;return expect(lexer,_lexer.TokenKind.DOLLAR),{kind:_kinds.VARIABLE,name:parseName(lexer),loc:loc(lexer,start)}}function parseSelectionSet(lexer){var start=lexer.token;return{kind:_kinds.SELECTION_SET,selections:many(lexer,_lexer.TokenKind.BRACE_L,parseSelection,_lexer.TokenKind.BRACE_R),loc:loc(lexer,start)}}function parseSelection(lexer){return peek(lexer,_lexer.TokenKind.SPREAD)?parseFragment(lexer):parseField(lexer)}function parseField(lexer){var start=lexer.token,nameOrAlias=parseName(lexer),alias=void 0,name=void 0;return skip(lexer,_lexer.TokenKind.COLON)?(alias=nameOrAlias,name=parseName(lexer)):(alias=null,name=nameOrAlias),{kind:_kinds.FIELD,alias:alias,name:name,arguments:parseArguments(lexer),directives:parseDirectives(lexer),selectionSet:peek(lexer,_lexer.TokenKind.BRACE_L)?parseSelectionSet(lexer):null,loc:loc(lexer,start)}}function parseArguments(lexer){return peek(lexer,_lexer.TokenKind.PAREN_L)?many(lexer,_lexer.TokenKind.PAREN_L,parseArgument,_lexer.TokenKind.PAREN_R):[]}function parseArgument(lexer){var start=lexer.token;return{kind:_kinds.ARGUMENT,name:parseName(lexer),value:(expect(lexer,_lexer.TokenKind.COLON),parseValueLiteral(lexer,!1)),loc:loc(lexer,start)}}function parseFragment(lexer){var start=lexer.token;if(expect(lexer,_lexer.TokenKind.SPREAD),peek(lexer,_lexer.TokenKind.NAME)&&"on"!==lexer.token.value)return{kind:_kinds.FRAGMENT_SPREAD,name:parseFragmentName(lexer),directives:parseDirectives(lexer),loc:loc(lexer,start)};var typeCondition=null;return"on"===lexer.token.value&&(lexer.advance(),typeCondition=parseNamedType(lexer)),{kind:_kinds.INLINE_FRAGMENT,typeCondition:typeCondition,directives:parseDirectives(lexer),selectionSet:parseSelectionSet(lexer),loc:loc(lexer,start)}}function parseFragmentDefinition(lexer){var start=lexer.token;return expectKeyword(lexer,"fragment"),{kind:_kinds.FRAGMENT_DEFINITION,name:parseFragmentName(lexer),typeCondition:(expectKeyword(lexer,"on"),parseNamedType(lexer)),directives:parseDirectives(lexer),selectionSet:parseSelectionSet(lexer),loc:loc(lexer,start)}}function parseFragmentName(lexer){if("on"===lexer.token.value)throw unexpected(lexer);return parseName(lexer)}function parseValueLiteral(lexer,isConst){var token=lexer.token;switch(token.kind){case _lexer.TokenKind.BRACKET_L:return parseList(lexer,isConst);case _lexer.TokenKind.BRACE_L:return parseObject(lexer,isConst);case _lexer.TokenKind.INT:return lexer.advance(),{kind:_kinds.INT,value:token.value,loc:loc(lexer,token)};case _lexer.TokenKind.FLOAT:return lexer.advance(),{kind:_kinds.FLOAT,value:token.value,loc:loc(lexer,token)};case _lexer.TokenKind.STRING:return lexer.advance(),{kind:_kinds.STRING,value:token.value,loc:loc(lexer,token)};case _lexer.TokenKind.NAME:return"true"===token.value||"false"===token.value?(lexer.advance(),{kind:_kinds.BOOLEAN,value:"true"===token.value,loc:loc(lexer,token)}):"null"===token.value?(lexer.advance(),{kind:_kinds.NULL,loc:loc(lexer,token)}):(lexer.advance(),{kind:_kinds.ENUM,value:token.value,loc:loc(lexer,token)});case _lexer.TokenKind.DOLLAR:if(!isConst)return parseVariable(lexer)}throw unexpected(lexer)}function parseConstValue(lexer){return parseValueLiteral(lexer,!0)}function parseValueValue(lexer){return parseValueLiteral(lexer,!1)}function parseList(lexer,isConst){var start=lexer.token,item=isConst?parseConstValue:parseValueValue;return{kind:_kinds.LIST,values:any(lexer,_lexer.TokenKind.BRACKET_L,item,_lexer.TokenKind.BRACKET_R),loc:loc(lexer,start)}}function parseObject(lexer,isConst){var start=lexer.token;expect(lexer,_lexer.TokenKind.BRACE_L);for(var fields=[];!skip(lexer,_lexer.TokenKind.BRACE_R);)fields.push(parseObjectField(lexer,isConst));return{kind:_kinds.OBJECT,fields:fields,loc:loc(lexer,start)}}function parseObjectField(lexer,isConst){var start=lexer.token;return{kind:_kinds.OBJECT_FIELD,name:parseName(lexer),value:(expect(lexer,_lexer.TokenKind.COLON),parseValueLiteral(lexer,isConst)),loc:loc(lexer,start)}}function parseDirectives(lexer){for(var directives=[];peek(lexer,_lexer.TokenKind.AT);)directives.push(parseDirective(lexer));return directives}function parseDirective(lexer){var start=lexer.token;return expect(lexer,_lexer.TokenKind.AT),{kind:_kinds.DIRECTIVE,name:parseName(lexer),arguments:parseArguments(lexer),loc:loc(lexer,start)}}function parseTypeReference(lexer){var start=lexer.token,type=void 0;return skip(lexer,_lexer.TokenKind.BRACKET_L)?(type=parseTypeReference(lexer),expect(lexer,_lexer.TokenKind.BRACKET_R),type={kind:_kinds.LIST_TYPE,type:type,loc:loc(lexer,start)}):type=parseNamedType(lexer),skip(lexer,_lexer.TokenKind.BANG)?{kind:_kinds.NON_NULL_TYPE,type:type,loc:loc(lexer,start)}:type}function parseNamedType(lexer){var start=lexer.token;return{kind:_kinds.NAMED_TYPE,name:parseName(lexer),loc:loc(lexer,start)}}function parseTypeSystemDefinition(lexer){if(peek(lexer,_lexer.TokenKind.NAME))switch(lexer.token.value){case"schema":return parseSchemaDefinition(lexer);case"scalar":return parseScalarTypeDefinition(lexer);case"type":return parseObjectTypeDefinition(lexer);case"interface":return parseInterfaceTypeDefinition(lexer);case"union":return parseUnionTypeDefinition(lexer);case"enum":return parseEnumTypeDefinition(lexer);case"input":return parseInputObjectTypeDefinition(lexer);case"extend":return parseTypeExtensionDefinition(lexer);case"directive":return parseDirectiveDefinition(lexer)}throw unexpected(lexer)}function parseSchemaDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"schema");var directives=parseDirectives(lexer),operationTypes=many(lexer,_lexer.TokenKind.BRACE_L,parseOperationTypeDefinition,_lexer.TokenKind.BRACE_R);return{kind:_kinds.SCHEMA_DEFINITION,directives:directives,operationTypes:operationTypes,loc:loc(lexer,start)}}function parseOperationTypeDefinition(lexer){var start=lexer.token,operation=parseOperationType(lexer);expect(lexer,_lexer.TokenKind.COLON);var type=parseNamedType(lexer);return{kind:_kinds.OPERATION_TYPE_DEFINITION,operation:operation,type:type,loc:loc(lexer,start)}}function parseScalarTypeDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"scalar");var name=parseName(lexer),directives=parseDirectives(lexer);return{kind:_kinds.SCALAR_TYPE_DEFINITION,name:name,directives:directives,loc:loc(lexer,start)}}function parseObjectTypeDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"type");var name=parseName(lexer),interfaces=parseImplementsInterfaces(lexer),directives=parseDirectives(lexer),fields=any(lexer,_lexer.TokenKind.BRACE_L,parseFieldDefinition,_lexer.TokenKind.BRACE_R);return{kind:_kinds.OBJECT_TYPE_DEFINITION,name:name,interfaces:interfaces,directives:directives,fields:fields,loc:loc(lexer,start)}}function parseImplementsInterfaces(lexer){var types=[];if("implements"===lexer.token.value){lexer.advance();do{types.push(parseNamedType(lexer))}while(peek(lexer,_lexer.TokenKind.NAME))}return types}function parseFieldDefinition(lexer){var start=lexer.token,name=parseName(lexer),args=parseArgumentDefs(lexer);expect(lexer,_lexer.TokenKind.COLON);var type=parseTypeReference(lexer),directives=parseDirectives(lexer);return{kind:_kinds.FIELD_DEFINITION,name:name,arguments:args,type:type,directives:directives,loc:loc(lexer,start)}}function parseArgumentDefs(lexer){return peek(lexer,_lexer.TokenKind.PAREN_L)?many(lexer,_lexer.TokenKind.PAREN_L,parseInputValueDef,_lexer.TokenKind.PAREN_R):[]}function parseInputValueDef(lexer){var start=lexer.token,name=parseName(lexer);expect(lexer,_lexer.TokenKind.COLON);var type=parseTypeReference(lexer),defaultValue=null;skip(lexer,_lexer.TokenKind.EQUALS)&&(defaultValue=parseConstValue(lexer));var directives=parseDirectives(lexer);return{kind:_kinds.INPUT_VALUE_DEFINITION,name:name,type:type,defaultValue:defaultValue,directives:directives,loc:loc(lexer,start)}}function parseInterfaceTypeDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"interface");var name=parseName(lexer),directives=parseDirectives(lexer),fields=any(lexer,_lexer.TokenKind.BRACE_L,parseFieldDefinition,_lexer.TokenKind.BRACE_R);return{kind:_kinds.INTERFACE_TYPE_DEFINITION,name:name,directives:directives,fields:fields,loc:loc(lexer,start)}}function parseUnionTypeDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"union");var name=parseName(lexer),directives=parseDirectives(lexer);expect(lexer,_lexer.TokenKind.EQUALS);var types=parseUnionMembers(lexer);return{kind:_kinds.UNION_TYPE_DEFINITION,name:name,directives:directives,types:types,loc:loc(lexer,start)}}function parseUnionMembers(lexer){skip(lexer,_lexer.TokenKind.PIPE);var members=[];do{members.push(parseNamedType(lexer))}while(skip(lexer,_lexer.TokenKind.PIPE));return members}function parseEnumTypeDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"enum");var name=parseName(lexer),directives=parseDirectives(lexer),values=many(lexer,_lexer.TokenKind.BRACE_L,parseEnumValueDefinition,_lexer.TokenKind.BRACE_R);return{kind:_kinds.ENUM_TYPE_DEFINITION,name:name,directives:directives,values:values,loc:loc(lexer,start)}}function parseEnumValueDefinition(lexer){var start=lexer.token,name=parseName(lexer),directives=parseDirectives(lexer);return{kind:_kinds.ENUM_VALUE_DEFINITION,name:name,directives:directives,loc:loc(lexer,start)}}function parseInputObjectTypeDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"input");var name=parseName(lexer),directives=parseDirectives(lexer),fields=any(lexer,_lexer.TokenKind.BRACE_L,parseInputValueDef,_lexer.TokenKind.BRACE_R);return{kind:_kinds.INPUT_OBJECT_TYPE_DEFINITION,name:name,directives:directives,fields:fields,loc:loc(lexer,start)}}function parseTypeExtensionDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"extend");var definition=parseObjectTypeDefinition(lexer);return{kind:_kinds.TYPE_EXTENSION_DEFINITION,definition:definition,loc:loc(lexer,start)}}function parseDirectiveDefinition(lexer){var start=lexer.token;expectKeyword(lexer,"directive"),expect(lexer,_lexer.TokenKind.AT);var name=parseName(lexer),args=parseArgumentDefs(lexer);expectKeyword(lexer,"on");var locations=parseDirectiveLocations(lexer);return{kind:_kinds.DIRECTIVE_DEFINITION,name:name,arguments:args,locations:locations,loc:loc(lexer,start)}}function parseDirectiveLocations(lexer){skip(lexer,_lexer.TokenKind.PIPE);var locations=[];do{locations.push(parseName(lexer))}while(skip(lexer,_lexer.TokenKind.PIPE));return locations}function loc(lexer,startToken){if(!lexer.options.noLocation)return new Loc(startToken,lexer.lastToken,lexer.source)}function Loc(startToken,endToken,source){this.start=startToken.start,this.end=endToken.end,this.startToken=startToken,this.endToken=endToken,this.source=source}function peek(lexer,kind){return lexer.token.kind===kind}function skip(lexer,kind){var match=lexer.token.kind===kind;return match&&lexer.advance(),match}function expect(lexer,kind){var token=lexer.token;if(token.kind===kind)return lexer.advance(),token;throw(0,_error.syntaxError)(lexer.source,token.start,"Expected "+kind+", found "+(0,_lexer.getTokenDesc)(token))}function expectKeyword(lexer,value){var token=lexer.token;if(token.kind===_lexer.TokenKind.NAME&&token.value===value)return lexer.advance(),token;throw(0,_error.syntaxError)(lexer.source,token.start,'Expected "'+value+'", found '+(0,_lexer.getTokenDesc)(token))}function unexpected(lexer,atToken){var token=atToken||lexer.token;return(0,_error.syntaxError)(lexer.source,token.start,"Unexpected "+(0,_lexer.getTokenDesc)(token))}function any(lexer,openKind,parseFn,closeKind){expect(lexer,openKind);for(var nodes=[];!skip(lexer,closeKind);)nodes.push(parseFn(lexer));return nodes}function many(lexer,openKind,parseFn,closeKind){expect(lexer,openKind);for(var nodes=[parseFn(lexer)];!skip(lexer,closeKind);)nodes.push(parseFn(lexer));return nodes}Object.defineProperty(exports,"__esModule",{value:!0}),exports.parse=function(source,options){var sourceObj="string"==typeof source?new _source.Source(source):source;if(!(sourceObj instanceof _source.Source))throw new TypeError("Must provide Source. Received: "+String(sourceObj));return parseDocument((0,_lexer.createLexer)(sourceObj,options||{}))},exports.parseValue=function(source,options){var sourceObj="string"==typeof source?new _source.Source(source):source,lexer=(0,_lexer.createLexer)(sourceObj,options||{});expect(lexer,_lexer.TokenKind.SOF);var value=parseValueLiteral(lexer,!1);return expect(lexer,_lexer.TokenKind.EOF),value},exports.parseType=function(source,options){var sourceObj="string"==typeof source?new _source.Source(source):source,lexer=(0,_lexer.createLexer)(sourceObj,options||{});expect(lexer,_lexer.TokenKind.SOF);var type=parseTypeReference(lexer);return expect(lexer,_lexer.TokenKind.EOF),type},exports.parseConstValue=parseConstValue,exports.parseTypeReference=parseTypeReference,exports.parseNamedType=parseNamedType;var _source=require("./source"),_error=require("../error"),_lexer=require("./lexer"),_kinds=require("./kinds");Loc.prototype.toJSON=Loc.prototype.inspect=function(){return{start:this.start,end:this.end}}},{"../error":85,"./kinds":102,"./lexer":103,"./source":107}],106:[function(require,module,exports){"use strict";function join(maybeArray,separator){return maybeArray?maybeArray.filter(function(x){return x}).join(separator||""):""}function block(array){return array&&0!==array.length?indent("{\n"+join(array,"\n"))+"\n}":"{}"}function wrap(start,maybeString,end){return maybeString?start+maybeString+(end||""):""}function indent(maybeString){return maybeString&&maybeString.replace(/\n/g,"\n ")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.print=function(ast){return(0,_visitor.visit)(ast,{leave:printDocASTReducer})};var _visitor=require("./visitor"),printDocASTReducer={Name:function(node){return node.value},Variable:function(node){return"$"+node.name},Document:function(node){return join(node.definitions,"\n\n")+"\n"},OperationDefinition:function(node){var op=node.operation,name=node.name,varDefs=wrap("(",join(node.variableDefinitions,", "),")"),directives=join(node.directives," "),selectionSet=node.selectionSet;return name||directives||varDefs||"query"!==op?join([op,join([name,varDefs]),directives,selectionSet]," "):selectionSet},VariableDefinition:function(_ref){return _ref.variable+": "+_ref.type+wrap(" = ",_ref.defaultValue)},SelectionSet:function(_ref2){return block(_ref2.selections)},Field:function(_ref3){var alias=_ref3.alias,name=_ref3.name,args=_ref3.arguments,directives=_ref3.directives,selectionSet=_ref3.selectionSet;return join([wrap("",alias,": ")+name+wrap("(",join(args,", "),")"),join(directives," "),selectionSet]," ")},Argument:function(_ref4){return _ref4.name+": "+_ref4.value},FragmentSpread:function(_ref5){return"..."+_ref5.name+wrap(" ",join(_ref5.directives," "))},InlineFragment:function(_ref6){var typeCondition=_ref6.typeCondition,directives=_ref6.directives,selectionSet=_ref6.selectionSet;return join(["...",wrap("on ",typeCondition),join(directives," "),selectionSet]," ")},FragmentDefinition:function(_ref7){var name=_ref7.name,typeCondition=_ref7.typeCondition,directives=_ref7.directives,selectionSet=_ref7.selectionSet;return"fragment "+name+" on "+typeCondition+" "+wrap("",join(directives," ")," ")+selectionSet},IntValue:function(_ref8){return _ref8.value},FloatValue:function(_ref9){return _ref9.value},StringValue:function(_ref10){var value=_ref10.value;return JSON.stringify(value)},BooleanValue:function(_ref11){var value=_ref11.value;return JSON.stringify(value)},NullValue:function(){return"null"},EnumValue:function(_ref12){return _ref12.value},ListValue:function(_ref13){return"["+join(_ref13.values,", ")+"]"},ObjectValue:function(_ref14){return"{"+join(_ref14.fields,", ")+"}"},ObjectField:function(_ref15){return _ref15.name+": "+_ref15.value},Directive:function(_ref16){return"@"+_ref16.name+wrap("(",join(_ref16.arguments,", "),")")},NamedType:function(_ref17){return _ref17.name},ListType:function(_ref18){return"["+_ref18.type+"]"},NonNullType:function(_ref19){return _ref19.type+"!"},SchemaDefinition:function(_ref20){var directives=_ref20.directives,operationTypes=_ref20.operationTypes;return join(["schema",join(directives," "),block(operationTypes)]," ")},OperationTypeDefinition:function(_ref21){return _ref21.operation+": "+_ref21.type},ScalarTypeDefinition:function(_ref22){return join(["scalar",_ref22.name,join(_ref22.directives," ")]," ")},ObjectTypeDefinition:function(_ref23){var name=_ref23.name,interfaces=_ref23.interfaces,directives=_ref23.directives,fields=_ref23.fields;return join(["type",name,wrap("implements ",join(interfaces,", ")),join(directives," "),block(fields)]," ")},FieldDefinition:function(_ref24){var name=_ref24.name,args=_ref24.arguments,type=_ref24.type,directives=_ref24.directives;return name+wrap("(",join(args,", "),")")+": "+type+wrap(" ",join(directives," "))},InputValueDefinition:function(_ref25){var name=_ref25.name,type=_ref25.type,defaultValue=_ref25.defaultValue,directives=_ref25.directives;return join([name+": "+type,wrap("= ",defaultValue),join(directives," ")]," ")},InterfaceTypeDefinition:function(_ref26){var name=_ref26.name,directives=_ref26.directives,fields=_ref26.fields;return join(["interface",name,join(directives," "),block(fields)]," ")},UnionTypeDefinition:function(_ref27){var name=_ref27.name,directives=_ref27.directives,types=_ref27.types;return join(["union",name,join(directives," "),"= "+join(types," | ")]," ")},EnumTypeDefinition:function(_ref28){var name=_ref28.name,directives=_ref28.directives,values=_ref28.values;return join(["enum",name,join(directives," "),block(values)]," ")},EnumValueDefinition:function(_ref29){return join([_ref29.name,join(_ref29.directives," ")]," ")},InputObjectTypeDefinition:function(_ref30){var name=_ref30.name,directives=_ref30.directives,fields=_ref30.fields;return join(["input",name,join(directives," "),block(fields)]," ")},TypeExtensionDefinition:function(_ref31){return"extend "+_ref31.definition},DirectiveDefinition:function(_ref32){var name=_ref32.name,args=_ref32.arguments,locations=_ref32.locations;return"directive @"+name+wrap("(",join(args,", "),")")+" on "+join(locations," | ")}}},{"./visitor":108}],107:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:!0});exports.Source=function Source(body,name){_classCallCheck(this,Source),this.body=body,this.name=name||"GraphQL request"}},{}],108:[function(require,module,exports){"use strict";function isNode(maybeNode){return maybeNode&&"string"==typeof maybeNode.kind}function getVisitFn(visitor,kind,isLeaving){var kindVisitor=visitor[kind];if(kindVisitor){if(!isLeaving&&"function"==typeof kindVisitor)return kindVisitor;var kindSpecificVisitor=isLeaving?kindVisitor.leave:kindVisitor.enter;if("function"==typeof kindSpecificVisitor)return kindSpecificVisitor}else{var specificVisitor=isLeaving?visitor.leave:visitor.enter;if(specificVisitor){if("function"==typeof specificVisitor)return specificVisitor;var specificKindVisitor=specificVisitor[kind];if("function"==typeof specificKindVisitor)return specificKindVisitor}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.visit=function(root,visitor,keyMap){var visitorKeys=keyMap||QueryDocumentKeys,stack=void 0,inArray=Array.isArray(root),keys=[root],index=-1,edits=[],parent=void 0,path=[],ancestors=[],newRoot=root;do{var isLeaving=++index===keys.length,key=void 0,node=void 0,isEdited=isLeaving&&0!==edits.length;if(isLeaving){if(key=0===ancestors.length?void 0:path.pop(),node=parent,parent=ancestors.pop(),isEdited){if(inArray)node=node.slice();else{var clone={};for(var k in node)node.hasOwnProperty(k)&&(clone[k]=node[k]);node=clone}for(var editOffset=0,ii=0;ii<edits.length;ii++){var editKey=edits[ii][0],editValue=edits[ii][1];inArray&&(editKey-=editOffset),inArray&&null===editValue?(node.splice(editKey,1),editOffset++):node[editKey]=editValue}}index=stack.index,keys=stack.keys,edits=stack.edits,inArray=stack.inArray,stack=stack.prev}else{if(key=parent?inArray?index:keys[index]:void 0,null===(node=parent?parent[key]:newRoot)||void 0===node)continue;parent&&path.push(key)}var result=void 0;if(!Array.isArray(node)){if(!isNode(node))throw new Error("Invalid AST Node: "+JSON.stringify(node));var visitFn=getVisitFn(visitor,node.kind,isLeaving);if(visitFn){if((result=visitFn.call(visitor,node,key,parent,path,ancestors))===BREAK)break;if(!1===result){if(!isLeaving){path.pop();continue}}else if(void 0!==result&&(edits.push([key,result]),!isLeaving)){if(!isNode(result)){path.pop();continue}node=result}}}void 0===result&&isEdited&&edits.push([key,node]),isLeaving||(stack={inArray:inArray,index:index,keys:keys,edits:edits,prev:stack},keys=(inArray=Array.isArray(node))?node:visitorKeys[node.kind]||[],index=-1,edits=[],parent&&ancestors.push(parent),parent=node)}while(void 0!==stack);return 0!==edits.length&&(newRoot=edits[edits.length-1][1]),newRoot},exports.visitInParallel=function(visitors){var skipping=new Array(visitors.length);return{enter:function(node){for(var i=0;i<visitors.length;i++)if(!skipping[i]){var fn=getVisitFn(visitors[i],node.kind,!1);if(fn){var result=fn.apply(visitors[i],arguments);if(!1===result)skipping[i]=node;else if(result===BREAK)skipping[i]=BREAK;else if(void 0!==result)return result}}},leave:function(node){for(var i=0;i<visitors.length;i++)if(skipping[i])skipping[i]===node&&(skipping[i]=null);else{var fn=getVisitFn(visitors[i],node.kind,!0);if(fn){var result=fn.apply(visitors[i],arguments);if(result===BREAK)skipping[i]=BREAK;else if(void 0!==result&&!1!==result)return result}}}}},exports.visitWithTypeInfo=function(typeInfo,visitor){return{enter:function(node){typeInfo.enter(node);var fn=getVisitFn(visitor,node.kind,!1);if(fn){var result=fn.apply(visitor,arguments);return void 0!==result&&(typeInfo.leave(node),isNode(result)&&typeInfo.enter(result)),result}},leave:function(node){var fn=getVisitFn(visitor,node.kind,!0),result=void 0;return fn&&(result=fn.apply(visitor,arguments)),typeInfo.leave(node),result}}},exports.getVisitFn=getVisitFn;var QueryDocumentKeys=exports.QueryDocumentKeys={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["name","directives"],ObjectTypeDefinition:["name","interfaces","directives","fields"],FieldDefinition:["name","arguments","type","directives"],InputValueDefinition:["name","type","defaultValue","directives"],InterfaceTypeDefinition:["name","directives","fields"],UnionTypeDefinition:["name","directives","types"],EnumTypeDefinition:["name","directives","values"],EnumValueDefinition:["name","directives"],InputObjectTypeDefinition:["name","directives","fields"],TypeExtensionDefinition:["definition"],DirectiveDefinition:["name","arguments","locations"]},BREAK=exports.BREAK={}},{}],109:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _subscribe=require("./subscribe");Object.defineProperty(exports,"subscribe",{enumerable:!0,get:function(){return _subscribe.subscribe}}),Object.defineProperty(exports,"createSourceEventStream",{enumerable:!0,get:function(){return _subscribe.createSourceEventStream}})},{"./subscribe":111}],110:[function(require,module,exports){"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function asyncMapValue(value,callback){return new Promise(function(resolve){return resolve(callback(value))})}function iteratorResult(value){return{value:value,done:!1}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(iterable,callback){function mapResult(result){return result.done?result:asyncMapValue(result.value,callback).then(iteratorResult,abruptClose)}var iterator=(0,_iterall.getAsyncIterator)(iterable),$return=void 0,abruptClose=void 0;return"function"==typeof iterator.return&&($return=iterator.return,abruptClose=function(error){var rethrow=function(){return Promise.reject(error)};return $return.call(iterator).then(rethrow,rethrow)}),_defineProperty({next:function(){return iterator.next().then(mapResult)},return:function(){return $return?$return.call(iterator).then(mapResult):Promise.resolve({value:void 0,done:!0})},throw:function(error){return"function"==typeof iterator.throw?iterator.throw(error).then(mapResult):Promise.reject(error).catch(abruptClose)}},_iterall.$$asyncIterator,function(){return this})};var _iterall=require("iterall")},{iterall:166}],111:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function subscribeImpl(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver,subscribeFieldResolver){var subscription=createSourceEventStream(schema,document,rootValue,contextValue,variableValues,operationName,subscribeFieldResolver);return(0,_mapAsyncIterator2.default)(subscription,function(payload){return(0,_execute.execute)(schema,document,payload,contextValue,variableValues,operationName,fieldResolver)})}function createSourceEventStream(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver){(0,_execute.assertValidExecutionArguments)(schema,document,variableValues);var exeContext=(0,_execute.buildExecutionContext)(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver),type=(0,_execute.getOperationRootType)(schema,exeContext.operation),fields=(0,_execute.collectFields)(exeContext,type,exeContext.operation.selectionSet,Object.create(null),Object.create(null)),responseName=Object.keys(fields)[0],fieldNodes=fields[responseName],fieldNode=fieldNodes[0],fieldDef=(0,_execute.getFieldDef)(schema,type,fieldNode.name.value);(0,_invariant2.default)(fieldDef,"This subscription is not defined by the schema.");var resolveFn=fieldDef.subscribe||exeContext.fieldResolver,info=(0,_execute.buildResolveInfo)(exeContext,fieldDef,fieldNodes,type,(0,_execute.addPath)(void 0,responseName)),subscription=(0,_execute.resolveFieldValueOrError)(exeContext,fieldDef,fieldNodes,resolveFn,rootValue,info);if(subscription instanceof Error)throw subscription;if(!(0,_iterall.isAsyncIterable)(subscription))throw new Error("Subscription must return Async Iterable. Received: "+String(subscription));return subscription}Object.defineProperty(exports,"__esModule",{value:!0}),exports.subscribe=function(argsOrSchema,document,rootValue,contextValue,variableValues,operationName,fieldResolver,subscribeFieldResolver){var args=1===arguments.length?argsOrSchema:void 0,schema=args?args.schema:argsOrSchema;return args?subscribeImpl(schema,args.document,args.rootValue,args.contextValue,args.variableValues,args.operationName,args.fieldResolver,args.subscribeFieldResolver):subscribeImpl(schema,document,rootValue,contextValue,variableValues,operationName,fieldResolver,subscribeFieldResolver)},exports.createSourceEventStream=createSourceEventStream;var _iterall=require("iterall"),_execute=require("../execution/execute"),_invariant2=(require("../type/schema"),_interopRequireDefault(require("../jsutils/invariant"))),_mapAsyncIterator2=_interopRequireDefault(require("./mapAsyncIterator"))},{"../execution/execute":88,"../jsutils/invariant":94,"../type/schema":117,"./mapAsyncIterator":110,iterall:166}],112:[function(require,module,exports){"use strict";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 isType(type){return type instanceof GraphQLScalarType||type instanceof GraphQLObjectType||type instanceof GraphQLInterfaceType||type instanceof GraphQLUnionType||type instanceof GraphQLEnumType||type instanceof GraphQLInputObjectType||type instanceof GraphQLList||type instanceof GraphQLNonNull}function isInputType(type){return type instanceof GraphQLScalarType||type instanceof GraphQLEnumType||type instanceof GraphQLInputObjectType||type instanceof GraphQLNonNull&&isInputType(type.ofType)||type instanceof GraphQLList&&isInputType(type.ofType)}function isOutputType(type){return type instanceof GraphQLScalarType||type instanceof GraphQLObjectType||type instanceof GraphQLInterfaceType||type instanceof GraphQLUnionType||type instanceof GraphQLEnumType||type instanceof GraphQLNonNull&&isOutputType(type.ofType)||type instanceof GraphQLList&&isOutputType(type.ofType)}function isLeafType(type){return type instanceof GraphQLScalarType||type instanceof GraphQLEnumType}function isCompositeType(type){return type instanceof GraphQLObjectType||type instanceof GraphQLInterfaceType||type instanceof GraphQLUnionType}function isAbstractType(type){return type instanceof GraphQLInterfaceType||type instanceof GraphQLUnionType}function isNamedType(type){return type instanceof GraphQLScalarType||type instanceof GraphQLObjectType||type instanceof GraphQLInterfaceType||type instanceof GraphQLUnionType||type instanceof GraphQLEnumType||type instanceof GraphQLInputObjectType}function resolveThunk(thunk){return"function"==typeof thunk?thunk():thunk}function defineInterfaces(type,interfacesThunk){var interfaces=resolveThunk(interfacesThunk);if(!interfaces)return[];(0,_invariant2.default)(Array.isArray(interfaces),type.name+" interfaces must be an Array or a function which returns an Array.");var implementedTypeNames=Object.create(null);return interfaces.forEach(function(iface){(0,_invariant2.default)(iface instanceof GraphQLInterfaceType,type.name+" may only implement Interface types, it cannot implement: "+String(iface)+"."),(0,_invariant2.default)(!implementedTypeNames[iface.name],type.name+" may declare it implements "+iface.name+" only once."),implementedTypeNames[iface.name]=!0,"function"!=typeof iface.resolveType&&(0,_invariant2.default)("function"==typeof type.isTypeOf,"Interface Type "+iface.name+' does not provide a "resolveType" function and implementing Type '+type.name+' does not provide a "isTypeOf" function. There is no way to resolve this implementing type during execution.')}),interfaces}function defineFieldMap(type,fieldsThunk){var fieldMap=resolveThunk(fieldsThunk);(0,_invariant2.default)(isPlainObj(fieldMap),type.name+" fields must be an object with field names as keys or a function which returns such an object.");var fieldNames=Object.keys(fieldMap);(0,_invariant2.default)(fieldNames.length>0,type.name+" fields must be an object with field names as keys or a function which returns such an object.");var resultFieldMap=Object.create(null);return fieldNames.forEach(function(fieldName){(0,_assertValidName.assertValidName)(fieldName);var fieldConfig=fieldMap[fieldName];(0,_invariant2.default)(isPlainObj(fieldConfig),type.name+"."+fieldName+" field config must be an object"),(0,_invariant2.default)(!fieldConfig.hasOwnProperty("isDeprecated"),type.name+"."+fieldName+' should provide "deprecationReason" instead of "isDeprecated".');var field=_extends({},fieldConfig,{isDeprecated:Boolean(fieldConfig.deprecationReason),name:fieldName});(0,_invariant2.default)(isOutputType(field.type),type.name+"."+fieldName+" field type must be Output Type but got: "+String(field.type)+"."),(0,_invariant2.default)(isValidResolver(field.resolve),type.name+"."+fieldName+" field resolver must be a function if provided, but got: "+String(field.resolve)+".");var argsConfig=fieldConfig.args;argsConfig?((0,_invariant2.default)(isPlainObj(argsConfig),type.name+"."+fieldName+" args must be an object with argument names as keys."),field.args=Object.keys(argsConfig).map(function(argName){(0,_assertValidName.assertValidName)(argName);var arg=argsConfig[argName];return(0,_invariant2.default)(isInputType(arg.type),type.name+"."+fieldName+"("+argName+":) argument type must be Input Type but got: "+String(arg.type)+"."),{name:argName,description:void 0===arg.description?null:arg.description,type:arg.type,defaultValue:arg.defaultValue}})):field.args=[],resultFieldMap[fieldName]=field}),resultFieldMap}function isPlainObj(obj){return obj&&"object"==typeof obj&&!Array.isArray(obj)}function isValidResolver(resolver){return null==resolver||"function"==typeof resolver}function defineTypes(unionType,typesThunk){var types=resolveThunk(typesThunk);(0,_invariant2.default)(Array.isArray(types)&&types.length>0,"Must provide Array of types or a function which returns such an array for Union "+unionType.name+".");var includedTypeNames=Object.create(null);return types.forEach(function(objType){(0,_invariant2.default)(objType instanceof GraphQLObjectType,unionType.name+" may only contain Object types, it cannot contain: "+String(objType)+"."),(0,_invariant2.default)(!includedTypeNames[objType.name],unionType.name+" can include "+objType.name+" type only once."),includedTypeNames[objType.name]=!0,"function"!=typeof unionType.resolveType&&(0,_invariant2.default)("function"==typeof objType.isTypeOf,'Union type "'+unionType.name+'" does not provide a "resolveType" function and possible type "'+objType.name+'" does not provide an "isTypeOf" function. There is no way to resolve this possible type during execution.')}),types}function defineEnumValues(type,valueMap){(0,_invariant2.default)(isPlainObj(valueMap),type.name+" values must be an object with value names as keys.");var valueNames=Object.keys(valueMap);return(0,_invariant2.default)(valueNames.length>0,type.name+" values must be an object with value names as keys."),valueNames.map(function(valueName){(0,_assertValidName.assertValidName)(valueName),(0,_invariant2.default)(-1===["true","false","null"].indexOf(valueName),'Name "'+valueName+'" can not be used as an Enum value.');var value=valueMap[valueName];return(0,_invariant2.default)(isPlainObj(value),type.name+"."+valueName+' must refer to an object with a "value" key representing an internal value but got: '+String(value)+"."),(0,_invariant2.default)(!value.hasOwnProperty("isDeprecated"),type.name+"."+valueName+' should provide "deprecationReason" instead of "isDeprecated".'),{name:valueName,description:value.description,isDeprecated:Boolean(value.deprecationReason),deprecationReason:value.deprecationReason,value:value.hasOwnProperty("value")?value.value:valueName}})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLNonNull=exports.GraphQLList=exports.GraphQLInputObjectType=exports.GraphQLEnumType=exports.GraphQLUnionType=exports.GraphQLInterfaceType=exports.GraphQLObjectType=exports.GraphQLScalarType=void 0;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target};exports.isType=isType,exports.assertType=function(type){return(0,_invariant2.default)(isType(type),"Expected "+String(type)+" to be a GraphQL type."),type},exports.isInputType=isInputType,exports.assertInputType=function(type){return(0,_invariant2.default)(isInputType(type),"Expected "+String(type)+" to be a GraphQL input type."),type},exports.isOutputType=isOutputType,exports.assertOutputType=function(type){return(0,_invariant2.default)(isOutputType(type),"Expected "+String(type)+" to be a GraphQL output type."),type},exports.isLeafType=isLeafType,exports.assertLeafType=function(type){return(0,_invariant2.default)(isLeafType(type),"Expected "+String(type)+" to be a GraphQL leaf type."),type},exports.isCompositeType=isCompositeType,exports.assertCompositeType=function(type){return(0,_invariant2.default)(isCompositeType(type),"Expected "+String(type)+" to be a GraphQL composite type."),type},exports.isAbstractType=isAbstractType,exports.assertAbstractType=function(type){return(0,_invariant2.default)(isAbstractType(type),"Expected "+String(type)+" to be a GraphQL abstract type."),type},exports.getNullableType=function(type){return type instanceof GraphQLNonNull?type.ofType:type},exports.isNamedType=isNamedType,exports.assertNamedType=function(type){return(0,_invariant2.default)(isNamedType(type),"Expected "+String(type)+" to be a GraphQL named type."),type},exports.getNamedType=function(type){if(type){for(var unmodifiedType=type;unmodifiedType instanceof GraphQLList||unmodifiedType instanceof GraphQLNonNull;)unmodifiedType=unmodifiedType.ofType;return unmodifiedType}};var _invariant2=_interopRequireDefault(require("../jsutils/invariant")),_isNullish2=_interopRequireDefault(require("../jsutils/isNullish")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_assertValidName=require("../utilities/assertValidName"),GraphQLScalarType=exports.GraphQLScalarType=function(){function GraphQLScalarType(config){_classCallCheck(this,GraphQLScalarType),(0,_assertValidName.assertValidName)(config.name),this.name=config.name,this.description=config.description,(0,_invariant2.default)("function"==typeof config.serialize,this.name+' must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.'),(config.parseValue||config.parseLiteral)&&(0,_invariant2.default)("function"==typeof config.parseValue&&"function"==typeof config.parseLiteral,this.name+' must provide both "parseValue" and "parseLiteral" functions.'),this._scalarConfig=config}return GraphQLScalarType.prototype.serialize=function(value){return(0,this._scalarConfig.serialize)(value)},GraphQLScalarType.prototype.isValidValue=function(value){return!(0,_isNullish2.default)(this.parseValue(value))},GraphQLScalarType.prototype.parseValue=function(value){var parser=this._scalarConfig.parseValue;return parser&&!(0,_isNullish2.default)(value)?parser(value):void 0},GraphQLScalarType.prototype.isValidLiteral=function(valueNode){return!(0,_isNullish2.default)(this.parseLiteral(valueNode))},GraphQLScalarType.prototype.parseLiteral=function(valueNode){var parser=this._scalarConfig.parseLiteral;return parser?parser(valueNode):void 0},GraphQLScalarType.prototype.toString=function(){return this.name},GraphQLScalarType}();GraphQLScalarType.prototype.toJSON=GraphQLScalarType.prototype.inspect=GraphQLScalarType.prototype.toString;var GraphQLObjectType=exports.GraphQLObjectType=function(){function GraphQLObjectType(config){_classCallCheck(this,GraphQLObjectType),(0,_assertValidName.assertValidName)(config.name,config.isIntrospection),this.name=config.name,this.description=config.description,config.isTypeOf&&(0,_invariant2.default)("function"==typeof config.isTypeOf,this.name+' must provide "isTypeOf" as a function.'),this.isTypeOf=config.isTypeOf,this._typeConfig=config}return GraphQLObjectType.prototype.getFields=function(){return this._fields||(this._fields=defineFieldMap(this,this._typeConfig.fields))},GraphQLObjectType.prototype.getInterfaces=function(){return this._interfaces||(this._interfaces=defineInterfaces(this,this._typeConfig.interfaces))},GraphQLObjectType.prototype.toString=function(){return this.name},GraphQLObjectType}();GraphQLObjectType.prototype.toJSON=GraphQLObjectType.prototype.inspect=GraphQLObjectType.prototype.toString;var GraphQLInterfaceType=exports.GraphQLInterfaceType=function(){function GraphQLInterfaceType(config){_classCallCheck(this,GraphQLInterfaceType),(0,_assertValidName.assertValidName)(config.name),this.name=config.name,this.description=config.description,config.resolveType&&(0,_invariant2.default)("function"==typeof config.resolveType,this.name+' must provide "resolveType" as a function.'),this.resolveType=config.resolveType,this._typeConfig=config}return GraphQLInterfaceType.prototype.getFields=function(){return this._fields||(this._fields=defineFieldMap(this,this._typeConfig.fields))},GraphQLInterfaceType.prototype.toString=function(){return this.name},GraphQLInterfaceType}();GraphQLInterfaceType.prototype.toJSON=GraphQLInterfaceType.prototype.inspect=GraphQLInterfaceType.prototype.toString;var GraphQLUnionType=exports.GraphQLUnionType=function(){function GraphQLUnionType(config){_classCallCheck(this,GraphQLUnionType),(0,_assertValidName.assertValidName)(config.name),this.name=config.name,this.description=config.description,config.resolveType&&(0,_invariant2.default)("function"==typeof config.resolveType,this.name+' must provide "resolveType" as a function.'),this.resolveType=config.resolveType,this._typeConfig=config}return GraphQLUnionType.prototype.getTypes=function(){return this._types||(this._types=defineTypes(this,this._typeConfig.types))},GraphQLUnionType.prototype.toString=function(){return this.name},GraphQLUnionType}();GraphQLUnionType.prototype.toJSON=GraphQLUnionType.prototype.inspect=GraphQLUnionType.prototype.toString;var GraphQLEnumType=exports.GraphQLEnumType=function(){function GraphQLEnumType(config){_classCallCheck(this,GraphQLEnumType),this.name=config.name,(0,_assertValidName.assertValidName)(config.name,config.isIntrospection),this.description=config.description,this._values=defineEnumValues(this,config.values),this._enumConfig=config}return GraphQLEnumType.prototype.getValues=function(){return this._values},GraphQLEnumType.prototype.getValue=function(name){return this._getNameLookup()[name]},GraphQLEnumType.prototype.serialize=function(value){var enumValue=this._getValueLookup().get(value);return enumValue?enumValue.name:null},GraphQLEnumType.prototype.isValidValue=function(value){return"string"==typeof value&&void 0!==this._getNameLookup()[value]},GraphQLEnumType.prototype.parseValue=function(value){if("string"==typeof value){var enumValue=this._getNameLookup()[value];if(enumValue)return enumValue.value}},GraphQLEnumType.prototype.isValidLiteral=function(valueNode){return valueNode.kind===Kind.ENUM&&void 0!==this._getNameLookup()[valueNode.value]},GraphQLEnumType.prototype.parseLiteral=function(valueNode){if(valueNode.kind===Kind.ENUM){var enumValue=this._getNameLookup()[valueNode.value];if(enumValue)return enumValue.value}},GraphQLEnumType.prototype._getValueLookup=function(){if(!this._valueLookup){var lookup=new Map;this.getValues().forEach(function(value){lookup.set(value.value,value)}),this._valueLookup=lookup}return this._valueLookup},GraphQLEnumType.prototype._getNameLookup=function(){if(!this._nameLookup){var lookup=Object.create(null);this.getValues().forEach(function(value){lookup[value.name]=value}),this._nameLookup=lookup}return this._nameLookup},GraphQLEnumType.prototype.toString=function(){return this.name},GraphQLEnumType}();GraphQLEnumType.prototype.toJSON=GraphQLEnumType.prototype.inspect=GraphQLEnumType.prototype.toString;var GraphQLInputObjectType=exports.GraphQLInputObjectType=function(){function GraphQLInputObjectType(config){_classCallCheck(this,GraphQLInputObjectType),(0,_assertValidName.assertValidName)(config.name),this.name=config.name,this.description=config.description,this._typeConfig=config}return GraphQLInputObjectType.prototype.getFields=function(){return this._fields||(this._fields=this._defineFieldMap())},GraphQLInputObjectType.prototype._defineFieldMap=function(){var _this=this,fieldMap=resolveThunk(this._typeConfig.fields);(0,_invariant2.default)(isPlainObj(fieldMap),this.name+" fields must be an object with field names as keys or a function which returns such an object.");var fieldNames=Object.keys(fieldMap);(0,_invariant2.default)(fieldNames.length>0,this.name+" fields must be an object with field names as keys or a function which returns such an object.");var resultFieldMap=Object.create(null);return fieldNames.forEach(function(fieldName){(0,_assertValidName.assertValidName)(fieldName);var field=_extends({},fieldMap[fieldName],{name:fieldName});(0,_invariant2.default)(isInputType(field.type),_this.name+"."+fieldName+" field type must be Input Type but got: "+String(field.type)+"."),(0,_invariant2.default)(null==field.resolve,_this.name+"."+fieldName+" field type has a resolve property, but Input Types cannot define resolvers."),resultFieldMap[fieldName]=field}),resultFieldMap},GraphQLInputObjectType.prototype.toString=function(){return this.name},GraphQLInputObjectType}();GraphQLInputObjectType.prototype.toJSON=GraphQLInputObjectType.prototype.inspect=GraphQLInputObjectType.prototype.toString;var GraphQLList=exports.GraphQLList=function(){function GraphQLList(type){_classCallCheck(this,GraphQLList),(0,_invariant2.default)(isType(type),"Can only create List of a GraphQLType but got: "+String(type)+"."),this.ofType=type}return GraphQLList.prototype.toString=function(){return"["+String(this.ofType)+"]"},GraphQLList}();GraphQLList.prototype.toJSON=GraphQLList.prototype.inspect=GraphQLList.prototype.toString;var GraphQLNonNull=exports.GraphQLNonNull=function(){function GraphQLNonNull(type){_classCallCheck(this,GraphQLNonNull),(0,_invariant2.default)(isType(type)&&!(type instanceof GraphQLNonNull),"Can only create NonNull of a Nullable GraphQLType but got: "+String(type)+"."),this.ofType=type}return GraphQLNonNull.prototype.toString=function(){return this.ofType.toString()+"!"},GraphQLNonNull}();GraphQLNonNull.prototype.toJSON=GraphQLNonNull.prototype.inspect=GraphQLNonNull.prototype.toString},{"../jsutils/invariant":94,"../jsutils/isNullish":96,"../language/kinds":102,"../utilities/assertValidName":119}],113:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.specifiedDirectives=exports.GraphQLDeprecatedDirective=exports.DEFAULT_DEPRECATION_REASON=exports.GraphQLSkipDirective=exports.GraphQLIncludeDirective=exports.GraphQLDirective=exports.DirectiveLocation=void 0;var _definition=require("./definition"),_scalars=require("./scalars"),_invariant2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../jsutils/invariant")),_assertValidName=require("../utilities/assertValidName"),DirectiveLocation=exports.DirectiveLocation={QUERY:"QUERY",MUTATION:"MUTATION",SUBSCRIPTION:"SUBSCRIPTION",FIELD:"FIELD",FRAGMENT_DEFINITION:"FRAGMENT_DEFINITION",FRAGMENT_SPREAD:"FRAGMENT_SPREAD",INLINE_FRAGMENT:"INLINE_FRAGMENT",SCHEMA:"SCHEMA",SCALAR:"SCALAR",OBJECT:"OBJECT",FIELD_DEFINITION:"FIELD_DEFINITION",ARGUMENT_DEFINITION:"ARGUMENT_DEFINITION",INTERFACE:"INTERFACE",UNION:"UNION",ENUM:"ENUM",ENUM_VALUE:"ENUM_VALUE",INPUT_OBJECT:"INPUT_OBJECT",INPUT_FIELD_DEFINITION:"INPUT_FIELD_DEFINITION"},GraphQLDirective=exports.GraphQLDirective=function GraphQLDirective(config){_classCallCheck(this,GraphQLDirective),(0,_invariant2.default)(config.name,"Directive must be named."),(0,_assertValidName.assertValidName)(config.name),(0,_invariant2.default)(Array.isArray(config.locations),"Must provide locations for directive."),this.name=config.name,this.description=config.description,this.locations=config.locations;var args=config.args;args?((0,_invariant2.default)(!Array.isArray(args),"@"+config.name+" args must be an object with argument names as keys."),this.args=Object.keys(args).map(function(argName){(0,_assertValidName.assertValidName)(argName);var arg=args[argName];return(0,_invariant2.default)((0,_definition.isInputType)(arg.type),"@"+config.name+"("+argName+":) argument type must be Input Type but got: "+String(arg.type)+"."),{name:argName,description:void 0===arg.description?null:arg.description,type:arg.type,defaultValue:arg.defaultValue}})):this.args=[]},GraphQLIncludeDirective=exports.GraphQLIncludeDirective=new GraphQLDirective({name:"include",description:"Directs the executor to include this field or fragment only when the `if` argument is true.",locations:[DirectiveLocation.FIELD,DirectiveLocation.FRAGMENT_SPREAD,DirectiveLocation.INLINE_FRAGMENT],args:{if:{type:new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),description:"Included when true."}}}),GraphQLSkipDirective=exports.GraphQLSkipDirective=new GraphQLDirective({name:"skip",description:"Directs the executor to skip this field or fragment when the `if` argument is true.",locations:[DirectiveLocation.FIELD,DirectiveLocation.FRAGMENT_SPREAD,DirectiveLocation.INLINE_FRAGMENT],args:{if:{type:new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),description:"Skipped when true."}}}),DEFAULT_DEPRECATION_REASON=exports.DEFAULT_DEPRECATION_REASON="No longer supported",GraphQLDeprecatedDirective=exports.GraphQLDeprecatedDirective=new GraphQLDirective({name:"deprecated",description:"Marks an element of a GraphQL schema as no longer supported.",locations:[DirectiveLocation.FIELD_DEFINITION,DirectiveLocation.ENUM_VALUE],args:{reason:{type:_scalars.GraphQLString,description:"Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted in [Markdown](https://daringfireball.net/projects/markdown/).",defaultValue:DEFAULT_DEPRECATION_REASON}}});exports.specifiedDirectives=[GraphQLIncludeDirective,GraphQLSkipDirective,GraphQLDeprecatedDirective]},{"../jsutils/invariant":94,"../utilities/assertValidName":119,"./definition":112,"./scalars":116}],114:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _schema=require("./schema");Object.defineProperty(exports,"GraphQLSchema",{enumerable:!0,get:function(){return _schema.GraphQLSchema}});var _definition=require("./definition");Object.defineProperty(exports,"isType",{enumerable:!0,get:function(){return _definition.isType}}),Object.defineProperty(exports,"isInputType",{enumerable:!0,get:function(){return _definition.isInputType}}),Object.defineProperty(exports,"isOutputType",{enumerable:!0,get:function(){return _definition.isOutputType}}),Object.defineProperty(exports,"isLeafType",{enumerable:!0,get:function(){return _definition.isLeafType}}),Object.defineProperty(exports,"isCompositeType",{enumerable:!0,get:function(){return _definition.isCompositeType}}),Object.defineProperty(exports,"isAbstractType",{enumerable:!0,get:function(){return _definition.isAbstractType}}),Object.defineProperty(exports,"isNamedType",{enumerable:!0,get:function(){return _definition.isNamedType}}),Object.defineProperty(exports,"assertType",{enumerable:!0,get:function(){return _definition.assertType}}),Object.defineProperty(exports,"assertInputType",{enumerable:!0,get:function(){return _definition.assertInputType}}),Object.defineProperty(exports,"assertOutputType",{enumerable:!0,get:function(){return _definition.assertOutputType}}),Object.defineProperty(exports,"assertLeafType",{enumerable:!0,get:function(){return _definition.assertLeafType}}),Object.defineProperty(exports,"assertCompositeType",{enumerable:!0,get:function(){return _definition.assertCompositeType}}),Object.defineProperty(exports,"assertAbstractType",{enumerable:!0,get:function(){return _definition.assertAbstractType}}),Object.defineProperty(exports,"assertNamedType",{enumerable:!0,get:function(){return _definition.assertNamedType}}),Object.defineProperty(exports,"getNullableType",{enumerable:!0,get:function(){return _definition.getNullableType}}),Object.defineProperty(exports,"getNamedType",{enumerable:!0,get:function(){return _definition.getNamedType}}),Object.defineProperty(exports,"GraphQLScalarType",{enumerable:!0,get:function(){return _definition.GraphQLScalarType}}),Object.defineProperty(exports,"GraphQLObjectType",{enumerable:!0,get:function(){return _definition.GraphQLObjectType}}),Object.defineProperty(exports,"GraphQLInterfaceType",{enumerable:!0,get:function(){return _definition.GraphQLInterfaceType}}),Object.defineProperty(exports,"GraphQLUnionType",{enumerable:!0,get:function(){return _definition.GraphQLUnionType}}),Object.defineProperty(exports,"GraphQLEnumType",{enumerable:!0,get:function(){return _definition.GraphQLEnumType}}),Object.defineProperty(exports,"GraphQLInputObjectType",{enumerable:!0,get:function(){return _definition.GraphQLInputObjectType}}),Object.defineProperty(exports,"GraphQLList",{enumerable:!0,get:function(){return _definition.GraphQLList}}),Object.defineProperty(exports,"GraphQLNonNull",{enumerable:!0,get:function(){return _definition.GraphQLNonNull}});var _directives=require("./directives");Object.defineProperty(exports,"DirectiveLocation",{enumerable:!0,get:function(){return _directives.DirectiveLocation}}),Object.defineProperty(exports,"GraphQLDirective",{enumerable:!0,get:function(){return _directives.GraphQLDirective}}),Object.defineProperty(exports,"specifiedDirectives",{enumerable:!0,get:function(){return _directives.specifiedDirectives}}),Object.defineProperty(exports,"GraphQLIncludeDirective",{enumerable:!0,get:function(){return _directives.GraphQLIncludeDirective}}),Object.defineProperty(exports,"GraphQLSkipDirective",{enumerable:!0,get:function(){return _directives.GraphQLSkipDirective}}),Object.defineProperty(exports,"GraphQLDeprecatedDirective",{enumerable:!0,get:function(){return _directives.GraphQLDeprecatedDirective}}),Object.defineProperty(exports,"DEFAULT_DEPRECATION_REASON",{enumerable:!0,get:function(){return _directives.DEFAULT_DEPRECATION_REASON}});var _scalars=require("./scalars");Object.defineProperty(exports,"GraphQLInt",{enumerable:!0,get:function(){return _scalars.GraphQLInt}}),Object.defineProperty(exports,"GraphQLFloat",{enumerable:!0,get:function(){return _scalars.GraphQLFloat}}),Object.defineProperty(exports,"GraphQLString",{enumerable:!0,get:function(){return _scalars.GraphQLString}}),Object.defineProperty(exports,"GraphQLBoolean",{enumerable:!0,get:function(){return _scalars.GraphQLBoolean}}),Object.defineProperty(exports,"GraphQLID",{enumerable:!0,get:function(){return _scalars.GraphQLID}});var _introspection=require("./introspection");Object.defineProperty(exports,"TypeKind",{enumerable:!0,get:function(){return _introspection.TypeKind}}),Object.defineProperty(exports,"__Schema",{enumerable:!0,get:function(){return _introspection.__Schema}}),Object.defineProperty(exports,"__Directive",{enumerable:!0,get:function(){return _introspection.__Directive}}),Object.defineProperty(exports,"__DirectiveLocation",{enumerable:!0,get:function(){return _introspection.__DirectiveLocation}}),Object.defineProperty(exports,"__Type",{enumerable:!0,get:function(){return _introspection.__Type}}),Object.defineProperty(exports,"__Field",{enumerable:!0,get:function(){return _introspection.__Field}}),Object.defineProperty(exports,"__InputValue",{enumerable:!0,get:function(){return _introspection.__InputValue}}),Object.defineProperty(exports,"__EnumValue",{enumerable:!0,get:function(){return _introspection.__EnumValue}}),Object.defineProperty(exports,"__TypeKind",{enumerable:!0,get:function(){return _introspection.__TypeKind}}),Object.defineProperty(exports,"SchemaMetaFieldDef",{enumerable:!0,get:function(){return _introspection.SchemaMetaFieldDef}}),Object.defineProperty(exports,"TypeMetaFieldDef",{enumerable:!0,get:function(){return _introspection.TypeMetaFieldDef}}),Object.defineProperty(exports,"TypeNameMetaFieldDef",{enumerable:!0,get:function(){return _introspection.TypeNameMetaFieldDef}})},{"./definition":112,"./directives":113,"./introspection":115,"./scalars":116,"./schema":117}],115:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TypeNameMetaFieldDef=exports.TypeMetaFieldDef=exports.SchemaMetaFieldDef=exports.__TypeKind=exports.TypeKind=exports.__EnumValue=exports.__InputValue=exports.__Field=exports.__Type=exports.__DirectiveLocation=exports.__Directive=exports.__Schema=void 0;var _isInvalid2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../jsutils/isInvalid")),_astFromValue=require("../utilities/astFromValue"),_printer=require("../language/printer"),_definition=require("./definition"),_scalars=require("./scalars"),_directives=require("./directives"),__Schema=exports.__Schema=new _definition.GraphQLObjectType({name:"__Schema",isIntrospection:!0,description:"A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.",fields:function(){return{types:{description:"A list of all types supported by this server.",type:new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))),resolve:function(schema){var typeMap=schema.getTypeMap();return Object.keys(typeMap).map(function(key){return typeMap[key]})}},queryType:{description:"The type that query operations will be rooted at.",type:new _definition.GraphQLNonNull(__Type),resolve:function(schema){return schema.getQueryType()}},mutationType:{description:"If this server supports mutation, the type that mutation operations will be rooted at.",type:__Type,resolve:function(schema){return schema.getMutationType()}},subscriptionType:{description:"If this server support subscription, the type that subscription operations will be rooted at.",type:__Type,resolve:function(schema){return schema.getSubscriptionType()}},directives:{description:"A list of all directives supported by this server.",type:new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))),resolve:function(schema){return schema.getDirectives()}}}}}),__Directive=exports.__Directive=new _definition.GraphQLObjectType({name:"__Directive",isIntrospection:!0,description:"A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.",fields:function(){return{name:{type:new _definition.GraphQLNonNull(_scalars.GraphQLString)},description:{type:_scalars.GraphQLString},locations:{type:new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__DirectiveLocation)))},args:{type:new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))),resolve:function(directive){return directive.args||[]}},onOperation:{deprecationReason:"Use `locations`.",type:new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),resolve:function(d){return-1!==d.locations.indexOf(_directives.DirectiveLocation.QUERY)||-1!==d.locations.indexOf(_directives.DirectiveLocation.MUTATION)||-1!==d.locations.indexOf(_directives.DirectiveLocation.SUBSCRIPTION)}},onFragment:{deprecationReason:"Use `locations`.",type:new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),resolve:function(d){return-1!==d.locations.indexOf(_directives.DirectiveLocation.FRAGMENT_SPREAD)||-1!==d.locations.indexOf(_directives.DirectiveLocation.INLINE_FRAGMENT)||-1!==d.locations.indexOf(_directives.DirectiveLocation.FRAGMENT_DEFINITION)}},onField:{deprecationReason:"Use `locations`.",type:new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),resolve:function(d){return-1!==d.locations.indexOf(_directives.DirectiveLocation.FIELD)}}}}}),__DirectiveLocation=exports.__DirectiveLocation=new _definition.GraphQLEnumType({name:"__DirectiveLocation",isIntrospection:!0,description:"A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.",values:{QUERY:{value:_directives.DirectiveLocation.QUERY,description:"Location adjacent to a query operation."},MUTATION:{value:_directives.DirectiveLocation.MUTATION,description:"Location adjacent to a mutation operation."},SUBSCRIPTION:{value:_directives.DirectiveLocation.SUBSCRIPTION,description:"Location adjacent to a subscription operation."},FIELD:{value:_directives.DirectiveLocation.FIELD,description:"Location adjacent to a field."},FRAGMENT_DEFINITION:{value:_directives.DirectiveLocation.FRAGMENT_DEFINITION,description:"Location adjacent to a fragment definition."},FRAGMENT_SPREAD:{value:_directives.DirectiveLocation.FRAGMENT_SPREAD,description:"Location adjacent to a fragment spread."},INLINE_FRAGMENT:{value:_directives.DirectiveLocation.INLINE_FRAGMENT,description:"Location adjacent to an inline fragment."},SCHEMA:{value:_directives.DirectiveLocation.SCHEMA,description:"Location adjacent to a schema definition."},SCALAR:{value:_directives.DirectiveLocation.SCALAR,description:"Location adjacent to a scalar definition."},OBJECT:{value:_directives.DirectiveLocation.OBJECT,description:"Location adjacent to an object type definition."},FIELD_DEFINITION:{value:_directives.DirectiveLocation.FIELD_DEFINITION,description:"Location adjacent to a field definition."},ARGUMENT_DEFINITION:{value:_directives.DirectiveLocation.ARGUMENT_DEFINITION,description:"Location adjacent to an argument definition."},INTERFACE:{value:_directives.DirectiveLocation.INTERFACE,description:"Location adjacent to an interface definition."},UNION:{value:_directives.DirectiveLocation.UNION,description:"Location adjacent to a union definition."},ENUM:{value:_directives.DirectiveLocation.ENUM,description:"Location adjacent to an enum definition."},ENUM_VALUE:{value:_directives.DirectiveLocation.ENUM_VALUE,description:"Location adjacent to an enum value definition."},INPUT_OBJECT:{value:_directives.DirectiveLocation.INPUT_OBJECT,description:"Location adjacent to an input object type definition."},INPUT_FIELD_DEFINITION:{value:_directives.DirectiveLocation.INPUT_FIELD_DEFINITION,description:"Location adjacent to an input object field definition."}}}),__Type=exports.__Type=new _definition.GraphQLObjectType({name:"__Type",isIntrospection:!0,description:"The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.",fields:function(){return{kind:{type:new _definition.GraphQLNonNull(__TypeKind),resolve:function(type){if(type instanceof _definition.GraphQLScalarType)return TypeKind.SCALAR;if(type instanceof _definition.GraphQLObjectType)return TypeKind.OBJECT;if(type instanceof _definition.GraphQLInterfaceType)return TypeKind.INTERFACE;if(type instanceof _definition.GraphQLUnionType)return TypeKind.UNION;if(type instanceof _definition.GraphQLEnumType)return TypeKind.ENUM;if(type instanceof _definition.GraphQLInputObjectType)return TypeKind.INPUT_OBJECT;if(type instanceof _definition.GraphQLList)return TypeKind.LIST;if(type instanceof _definition.GraphQLNonNull)return TypeKind.NON_NULL;throw new Error("Unknown kind of type: "+type)}},name:{type:_scalars.GraphQLString},description:{type:_scalars.GraphQLString},fields:{type:new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)),args:{includeDeprecated:{type:_scalars.GraphQLBoolean,defaultValue:!1}},resolve:function(type,_ref){var includeDeprecated=_ref.includeDeprecated;if(type instanceof _definition.GraphQLObjectType||type instanceof _definition.GraphQLInterfaceType){var fieldMap=type.getFields(),fields=Object.keys(fieldMap).map(function(fieldName){return fieldMap[fieldName]});return includeDeprecated||(fields=fields.filter(function(field){return!field.deprecationReason})),fields}return null}},interfaces:{type:new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)),resolve:function(type){if(type instanceof _definition.GraphQLObjectType)return type.getInterfaces()}},possibleTypes:{type:new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)),resolve:function(type,args,context,_ref2){var schema=_ref2.schema;if((0,_definition.isAbstractType)(type))return schema.getPossibleTypes(type)}},enumValues:{type:new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)),args:{includeDeprecated:{type:_scalars.GraphQLBoolean,defaultValue:!1}},resolve:function(type,_ref3){var includeDeprecated=_ref3.includeDeprecated;if(type instanceof _definition.GraphQLEnumType){var values=type.getValues();return includeDeprecated||(values=values.filter(function(value){return!value.deprecationReason})),values}}},inputFields:{type:new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)),resolve:function(type){if(type instanceof _definition.GraphQLInputObjectType){var fieldMap=type.getFields();return Object.keys(fieldMap).map(function(fieldName){return fieldMap[fieldName]})}}},ofType:{type:__Type}}}}),__Field=exports.__Field=new _definition.GraphQLObjectType({name:"__Field",isIntrospection:!0,description:"Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.",fields:function(){return{name:{type:new _definition.GraphQLNonNull(_scalars.GraphQLString)},description:{type:_scalars.GraphQLString},args:{type:new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))),resolve:function(field){return field.args||[]}},type:{type:new _definition.GraphQLNonNull(__Type)},isDeprecated:{type:new _definition.GraphQLNonNull(_scalars.GraphQLBoolean)},deprecationReason:{type:_scalars.GraphQLString}}}}),__InputValue=exports.__InputValue=new _definition.GraphQLObjectType({name:"__InputValue",isIntrospection:!0,description:"Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.",fields:function(){return{name:{type:new _definition.GraphQLNonNull(_scalars.GraphQLString)},description:{type:_scalars.GraphQLString},type:{type:new _definition.GraphQLNonNull(__Type)},defaultValue:{type:_scalars.GraphQLString,description:"A GraphQL-formatted string representing the default value for this input value.",resolve:function(inputVal){return(0,_isInvalid2.default)(inputVal.defaultValue)?null:(0,_printer.print)((0,_astFromValue.astFromValue)(inputVal.defaultValue,inputVal.type))}}}}}),__EnumValue=exports.__EnumValue=new _definition.GraphQLObjectType({name:"__EnumValue",isIntrospection:!0,description:"One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.",fields:function(){return{name:{type:new _definition.GraphQLNonNull(_scalars.GraphQLString)},description:{type:_scalars.GraphQLString},isDeprecated:{type:new _definition.GraphQLNonNull(_scalars.GraphQLBoolean)},deprecationReason:{type:_scalars.GraphQLString}}}}),TypeKind=exports.TypeKind={SCALAR:"SCALAR",OBJECT:"OBJECT",INTERFACE:"INTERFACE",UNION:"UNION",ENUM:"ENUM",INPUT_OBJECT:"INPUT_OBJECT",LIST:"LIST",NON_NULL:"NON_NULL"},__TypeKind=exports.__TypeKind=new _definition.GraphQLEnumType({name:"__TypeKind",isIntrospection:!0,description:"An enum describing what kind of type a given `__Type` is.",values:{SCALAR:{value:TypeKind.SCALAR,description:"Indicates this type is a scalar."},OBJECT:{value:TypeKind.OBJECT,description:"Indicates this type is an object. `fields` and `interfaces` are valid fields."},INTERFACE:{value:TypeKind.INTERFACE,description:"Indicates this type is an interface. `fields` and `possibleTypes` are valid fields."},UNION:{value:TypeKind.UNION,description:"Indicates this type is a union. `possibleTypes` is a valid field."},ENUM:{value:TypeKind.ENUM,description:"Indicates this type is an enum. `enumValues` is a valid field."},INPUT_OBJECT:{value:TypeKind.INPUT_OBJECT,description:"Indicates this type is an input object. `inputFields` is a valid field."},LIST:{value:TypeKind.LIST,description:"Indicates this type is a list. `ofType` is a valid field."},NON_NULL:{value:TypeKind.NON_NULL,description:"Indicates this type is a non-null. `ofType` is a valid field."}}});exports.SchemaMetaFieldDef={name:"__schema",type:new _definition.GraphQLNonNull(__Schema),description:"Access the current type schema of this server.",args:[],resolve:function(source,args,context,_ref4){return _ref4.schema}},exports.TypeMetaFieldDef={name:"__type",type:__Type,description:"Request the type information of a single type.",args:[{name:"name",type:new _definition.GraphQLNonNull(_scalars.GraphQLString)}],resolve:function(source,_ref5,context,_ref6){var name=_ref5.name;return _ref6.schema.getType(name)}},exports.TypeNameMetaFieldDef={name:"__typename",type:new _definition.GraphQLNonNull(_scalars.GraphQLString),description:"The name of the current Object type at runtime.",args:[],resolve:function(source,args,context,_ref7){return _ref7.parentType.name}}},{"../jsutils/isInvalid":95,"../language/printer":106,"../utilities/astFromValue":120,"./definition":112,"./directives":113,"./scalars":116}],116:[function(require,module,exports){"use strict";function coerceInt(value){if(""===value)throw new TypeError("Int cannot represent non 32-bit signed integer value: (empty string)");var num=Number(value);if(num!==num||num>MAX_INT||num<MIN_INT)throw new TypeError("Int cannot represent non 32-bit signed integer value: "+String(value));var int=Math.floor(num);if(int!==num)throw new TypeError("Int cannot represent non-integer value: "+String(value));return int}function coerceFloat(value){if(""===value)throw new TypeError("Float cannot represent non numeric value: (empty string)");var num=Number(value);if(num===num)return num;throw new TypeError("Float cannot represent non numeric value: "+String(value))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLID=exports.GraphQLBoolean=exports.GraphQLString=exports.GraphQLFloat=exports.GraphQLInt=void 0;var _definition=require("./definition"),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),MAX_INT=2147483647,MIN_INT=-2147483648;exports.GraphQLInt=new _definition.GraphQLScalarType({name:"Int",description:"The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. ",serialize:coerceInt,parseValue:coerceInt,parseLiteral:function(ast){if(ast.kind===Kind.INT){var num=parseInt(ast.value,10);if(num<=MAX_INT&&num>=MIN_INT)return num}return null}}),exports.GraphQLFloat=new _definition.GraphQLScalarType({name:"Float",description:"The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ",serialize:coerceFloat,parseValue:coerceFloat,parseLiteral:function(ast){return ast.kind===Kind.FLOAT||ast.kind===Kind.INT?parseFloat(ast.value):null}}),exports.GraphQLString=new _definition.GraphQLScalarType({name:"String",description:"The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.",serialize:String,parseValue:String,parseLiteral:function(ast){return ast.kind===Kind.STRING?ast.value:null}}),exports.GraphQLBoolean=new _definition.GraphQLScalarType({name:"Boolean",description:"The `Boolean` scalar type represents `true` or `false`.",serialize:Boolean,parseValue:Boolean,parseLiteral:function(ast){return ast.kind===Kind.BOOLEAN?ast.value:null}}),exports.GraphQLID=new _definition.GraphQLScalarType({name:"ID",description:'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.',serialize:String,parseValue:String,parseLiteral:function(ast){return ast.kind===Kind.STRING||ast.kind===Kind.INT?ast.value:null}})},{"../language/kinds":102,"./definition":112}],117:[function(require,module,exports){"use strict";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 typeMapReducer(map,type){if(!type)return map;if(type instanceof _definition.GraphQLList||type instanceof _definition.GraphQLNonNull)return typeMapReducer(map,type.ofType);if(map[type.name])return(0,_invariant2.default)(map[type.name]===type,'Schema must contain unique named types but contains multiple types named "'+type.name+'".'),map;map[type.name]=type;var reducedMap=map;if(type instanceof _definition.GraphQLUnionType&&(reducedMap=type.getTypes().reduce(typeMapReducer,reducedMap)),type instanceof _definition.GraphQLObjectType&&(reducedMap=type.getInterfaces().reduce(typeMapReducer,reducedMap)),type instanceof _definition.GraphQLObjectType||type instanceof _definition.GraphQLInterfaceType){var fieldMap=type.getFields();Object.keys(fieldMap).forEach(function(fieldName){var field=fieldMap[fieldName];if(field.args){var fieldArgTypes=field.args.map(function(arg){return arg.type});reducedMap=fieldArgTypes.reduce(typeMapReducer,reducedMap)}reducedMap=typeMapReducer(reducedMap,field.type)})}if(type instanceof _definition.GraphQLInputObjectType){var _fieldMap=type.getFields();Object.keys(_fieldMap).forEach(function(fieldName){var field=_fieldMap[fieldName];reducedMap=typeMapReducer(reducedMap,field.type)})}return reducedMap}function assertObjectImplementsInterface(schema,object,iface){var objectFieldMap=object.getFields(),ifaceFieldMap=iface.getFields();Object.keys(ifaceFieldMap).forEach(function(fieldName){var objectField=objectFieldMap[fieldName],ifaceField=ifaceFieldMap[fieldName];(0,_invariant2.default)(objectField,'"'+iface.name+'" expects field "'+fieldName+'" but "'+object.name+'" does not provide it.'),(0,_invariant2.default)((0,_typeComparators.isTypeSubTypeOf)(schema,objectField.type,ifaceField.type),iface.name+"."+fieldName+' expects type "'+String(ifaceField.type)+'" but '+object.name+"."+fieldName+' provides type "'+String(objectField.type)+'".'),ifaceField.args.forEach(function(ifaceArg){var argName=ifaceArg.name,objectArg=(0,_find2.default)(objectField.args,function(arg){return arg.name===argName});(0,_invariant2.default)(objectArg,iface.name+"."+fieldName+' expects argument "'+argName+'" but '+object.name+"."+fieldName+" does not provide it."),(0,_invariant2.default)((0,_typeComparators.isEqualType)(ifaceArg.type,objectArg.type),iface.name+"."+fieldName+"("+argName+':) expects type "'+String(ifaceArg.type)+'" but '+object.name+"."+fieldName+"("+argName+':) provides type "'+String(objectArg.type)+'".')}),objectField.args.forEach(function(objectArg){var argName=objectArg.name;(0,_find2.default)(ifaceField.args,function(arg){return arg.name===argName})||(0,_invariant2.default)(!(objectArg.type instanceof _definition.GraphQLNonNull),object.name+"."+fieldName+"("+argName+':) is of required type "'+String(objectArg.type)+'" but is not also provided by the interface '+iface.name+"."+fieldName+".")})})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.GraphQLSchema=void 0;var _definition=require("./definition"),_directives=require("./directives"),_introspection=require("./introspection"),_find2=_interopRequireDefault(require("../jsutils/find")),_invariant2=_interopRequireDefault(require("../jsutils/invariant")),_typeComparators=require("../utilities/typeComparators");exports.GraphQLSchema=function(){function GraphQLSchema(config){var _this=this;_classCallCheck(this,GraphQLSchema),(0,_invariant2.default)("object"==typeof config,"Must provide configuration object."),(0,_invariant2.default)(config.query instanceof _definition.GraphQLObjectType,"Schema query must be Object Type but got: "+String(config.query)+"."),this._queryType=config.query,(0,_invariant2.default)(!config.mutation||config.mutation instanceof _definition.GraphQLObjectType,"Schema mutation must be Object Type if provided but got: "+String(config.mutation)+"."),this._mutationType=config.mutation,(0,_invariant2.default)(!config.subscription||config.subscription instanceof _definition.GraphQLObjectType,"Schema subscription must be Object Type if provided but got: "+String(config.subscription)+"."),this._subscriptionType=config.subscription,(0,_invariant2.default)(!config.types||Array.isArray(config.types),"Schema types must be Array if provided but got: "+String(config.types)+"."),(0,_invariant2.default)(!config.directives||Array.isArray(config.directives)&&config.directives.every(function(directive){return directive instanceof _directives.GraphQLDirective}),"Schema directives must be Array<GraphQLDirective> if provided but got: "+String(config.directives)+"."),this._directives=config.directives||_directives.specifiedDirectives;var initialTypes=[this.getQueryType(),this.getMutationType(),this.getSubscriptionType(),_introspection.__Schema],types=config.types;types&&(initialTypes=initialTypes.concat(types)),this._typeMap=initialTypes.reduce(typeMapReducer,Object.create(null)),this._implementations=Object.create(null),Object.keys(this._typeMap).forEach(function(typeName){var type=_this._typeMap[typeName];type instanceof _definition.GraphQLObjectType&&type.getInterfaces().forEach(function(iface){var impls=_this._implementations[iface.name];impls?impls.push(type):_this._implementations[iface.name]=[type]})}),Object.keys(this._typeMap).forEach(function(typeName){var type=_this._typeMap[typeName];type instanceof _definition.GraphQLObjectType&&type.getInterfaces().forEach(function(iface){return assertObjectImplementsInterface(_this,type,iface)})})}return GraphQLSchema.prototype.getQueryType=function(){return this._queryType},GraphQLSchema.prototype.getMutationType=function(){return this._mutationType},GraphQLSchema.prototype.getSubscriptionType=function(){return this._subscriptionType},GraphQLSchema.prototype.getTypeMap=function(){return this._typeMap},GraphQLSchema.prototype.getType=function(name){return this.getTypeMap()[name]},GraphQLSchema.prototype.getPossibleTypes=function(abstractType){return abstractType instanceof _definition.GraphQLUnionType?abstractType.getTypes():((0,_invariant2.default)(abstractType instanceof _definition.GraphQLInterfaceType),this._implementations[abstractType.name])},GraphQLSchema.prototype.isPossibleType=function(abstractType,possibleType){var possibleTypeMap=this._possibleTypeMap;if(possibleTypeMap||(this._possibleTypeMap=possibleTypeMap=Object.create(null)),!possibleTypeMap[abstractType.name]){var possibleTypes=this.getPossibleTypes(abstractType);(0,_invariant2.default)(Array.isArray(possibleTypes),"Could not find possible implementing types for "+abstractType.name+" in schema. Check that schema.types is defined and is an array of all possible types in the schema."),possibleTypeMap[abstractType.name]=possibleTypes.reduce(function(map,type){return map[type.name]=!0,map},Object.create(null))}return Boolean(possibleTypeMap[abstractType.name][possibleType.name])},GraphQLSchema.prototype.getDirectives=function(){return this._directives},GraphQLSchema.prototype.getDirective=function(name){return(0,_find2.default)(this.getDirectives(),function(directive){return directive.name===name})},GraphQLSchema}()},{"../jsutils/find":93,"../jsutils/invariant":94,"../utilities/typeComparators":134,"./definition":112,"./directives":113,"./introspection":115}],118:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function getFieldDef(schema,parentType,fieldNode){var name=fieldNode.name.value;return name===_introspection.SchemaMetaFieldDef.name&&schema.getQueryType()===parentType?_introspection.SchemaMetaFieldDef:name===_introspection.TypeMetaFieldDef.name&&schema.getQueryType()===parentType?_introspection.TypeMetaFieldDef:name===_introspection.TypeNameMetaFieldDef.name&&(0,_definition.isCompositeType)(parentType)?_introspection.TypeNameMetaFieldDef:parentType instanceof _definition.GraphQLObjectType||parentType instanceof _definition.GraphQLInterfaceType?parentType.getFields()[name]:void 0}Object.defineProperty(exports,"__esModule",{value:!0}),exports.TypeInfo=void 0;var Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_definition=require("../type/definition"),_introspection=require("../type/introspection"),_typeFromAST=require("./typeFromAST"),_find2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../jsutils/find"));exports.TypeInfo=function(){function TypeInfo(schema,getFieldDefFn){_classCallCheck(this,TypeInfo),this._schema=schema,this._typeStack=[],this._parentTypeStack=[],this._inputTypeStack=[],this._fieldDefStack=[],this._directive=null,this._argument=null,this._enumValue=null,this._getFieldDef=getFieldDefFn||getFieldDef}return TypeInfo.prototype.getType=function(){if(this._typeStack.length>0)return this._typeStack[this._typeStack.length-1]},TypeInfo.prototype.getParentType=function(){if(this._parentTypeStack.length>0)return this._parentTypeStack[this._parentTypeStack.length-1]},TypeInfo.prototype.getInputType=function(){if(this._inputTypeStack.length>0)return this._inputTypeStack[this._inputTypeStack.length-1]},TypeInfo.prototype.getFieldDef=function(){if(this._fieldDefStack.length>0)return this._fieldDefStack[this._fieldDefStack.length-1]},TypeInfo.prototype.getDirective=function(){return this._directive},TypeInfo.prototype.getArgument=function(){return this._argument},TypeInfo.prototype.getEnumValue=function(){return this._enumValue},TypeInfo.prototype.enter=function(node){var schema=this._schema;switch(node.kind){case Kind.SELECTION_SET:var namedType=(0,_definition.getNamedType)(this.getType());this._parentTypeStack.push((0,_definition.isCompositeType)(namedType)?namedType:void 0);break;case Kind.FIELD:var parentType=this.getParentType(),fieldDef=void 0;parentType&&(fieldDef=this._getFieldDef(schema,parentType,node)),this._fieldDefStack.push(fieldDef),this._typeStack.push(fieldDef&&fieldDef.type);break;case Kind.DIRECTIVE:this._directive=schema.getDirective(node.name.value);break;case Kind.OPERATION_DEFINITION:var type=void 0;"query"===node.operation?type=schema.getQueryType():"mutation"===node.operation?type=schema.getMutationType():"subscription"===node.operation&&(type=schema.getSubscriptionType()),this._typeStack.push(type);break;case Kind.INLINE_FRAGMENT:case Kind.FRAGMENT_DEFINITION:var typeConditionAST=node.typeCondition,outputType=typeConditionAST?(0,_typeFromAST.typeFromAST)(schema,typeConditionAST):this.getType();this._typeStack.push((0,_definition.isOutputType)(outputType)?outputType:void 0);break;case Kind.VARIABLE_DEFINITION:var inputType=(0,_typeFromAST.typeFromAST)(schema,node.type);this._inputTypeStack.push((0,_definition.isInputType)(inputType)?inputType:void 0);break;case Kind.ARGUMENT:var argDef=void 0,argType=void 0,fieldOrDirective=this.getDirective()||this.getFieldDef();fieldOrDirective&&(argDef=(0,_find2.default)(fieldOrDirective.args,function(arg){return arg.name===node.name.value}))&&(argType=argDef.type),this._argument=argDef,this._inputTypeStack.push(argType);break;case Kind.LIST:var listType=(0,_definition.getNullableType)(this.getInputType());this._inputTypeStack.push(listType instanceof _definition.GraphQLList?listType.ofType:void 0);break;case Kind.OBJECT_FIELD:var objectType=(0,_definition.getNamedType)(this.getInputType()),fieldType=void 0;if(objectType instanceof _definition.GraphQLInputObjectType){var inputField=objectType.getFields()[node.name.value];fieldType=inputField?inputField.type:void 0}this._inputTypeStack.push(fieldType);break;case Kind.ENUM:var enumType=(0,_definition.getNamedType)(this.getInputType()),enumValue=void 0;enumType instanceof _definition.GraphQLEnumType&&(enumValue=enumType.getValue(node.value)),this._enumValue=enumValue}},TypeInfo.prototype.leave=function(node){switch(node.kind){case Kind.SELECTION_SET:this._parentTypeStack.pop();break;case Kind.FIELD:this._fieldDefStack.pop(),this._typeStack.pop();break;case Kind.DIRECTIVE:this._directive=null;break;case Kind.OPERATION_DEFINITION:case Kind.INLINE_FRAGMENT:case Kind.FRAGMENT_DEFINITION:this._typeStack.pop();break;case Kind.VARIABLE_DEFINITION:this._inputTypeStack.pop();break;case Kind.ARGUMENT:this._argument=null,this._inputTypeStack.pop();break;case Kind.LIST:case Kind.OBJECT_FIELD:this._inputTypeStack.pop();break;case Kind.ENUM:this._enumValue=null}},TypeInfo}()},{"../jsutils/find":93,"../language/kinds":102,"../type/definition":112,"../type/introspection":115,"./typeFromAST":135}],119:[function(require,module,exports){(function(process){"use strict";function formatWarning(error){var formatted="",errorString=String(error).replace(ERROR_PREFIX_RX,""),stack=error.stack;return stack&&(formatted=stack.replace(ERROR_PREFIX_RX,"")),-1===formatted.indexOf(errorString)&&(formatted=errorString+"\n"+formatted),formatted.trim()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.assertValidName=function(name,isIntrospection){if(!name||"string"!=typeof name)throw new Error("Must be named. Unexpected name: "+name+".");if(!isIntrospection&&!hasWarnedAboutDunder&&!noNameWarning&&"__"===name.slice(0,2)&&(hasWarnedAboutDunder=!0,console&&console.warn)){var error=new Error('Name "'+name+'" must not begin with "__", which is reserved by GraphQL introspection. In a future release of graphql this will become a hard error.');console.warn(formatWarning(error))}if(!NAME_RX.test(name))throw new Error('Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "'+name+'" does not.')},exports.formatWarning=formatWarning;var NAME_RX=/^[_a-zA-Z][_a-zA-Z0-9]*$/,ERROR_PREFIX_RX=/^Error: /,noNameWarning=Boolean(process&&process.env&&process.env.GRAPHQL_NO_NAME_WARNING),hasWarnedAboutDunder=!1}).call(this,require("_process"))},{_process:168}],120:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function astFromValue(value,type){var _value=value;if(type instanceof _definition.GraphQLNonNull){var astValue=astFromValue(_value,type.ofType);return astValue&&astValue.kind===Kind.NULL?null:astValue}if(null===_value)return{kind:Kind.NULL};if((0,_isInvalid2.default)(_value))return null;if(type instanceof _definition.GraphQLList){var itemType=type.ofType;if((0,_iterall.isCollection)(_value)){var valuesNodes=[];return(0,_iterall.forEach)(_value,function(item){var itemNode=astFromValue(item,itemType);itemNode&&valuesNodes.push(itemNode)}),{kind:Kind.LIST,values:valuesNodes}}return astFromValue(_value,itemType)}if(type instanceof _definition.GraphQLInputObjectType){if(null===_value||"object"!=typeof _value)return null;var fields=type.getFields(),fieldNodes=[];return Object.keys(fields).forEach(function(fieldName){var fieldType=fields[fieldName].type,fieldValue=astFromValue(_value[fieldName],fieldType);fieldValue&&fieldNodes.push({kind:Kind.OBJECT_FIELD,name:{kind:Kind.NAME,value:fieldName},value:fieldValue})}),{kind:Kind.OBJECT,fields:fieldNodes}}(0,_invariant2.default)(type instanceof _definition.GraphQLScalarType||type instanceof _definition.GraphQLEnumType,"Must provide Input Type, cannot use: "+String(type));var serialized=type.serialize(_value);if((0,_isNullish2.default)(serialized))return null;if("boolean"==typeof serialized)return{kind:Kind.BOOLEAN,value:serialized};if("number"==typeof serialized){var stringNum=String(serialized);return/^[0-9]+$/.test(stringNum)?{kind:Kind.INT,value:stringNum}:{kind:Kind.FLOAT,value:stringNum}}if("string"==typeof serialized)return type instanceof _definition.GraphQLEnumType?{kind:Kind.ENUM,value:serialized}:type===_scalars.GraphQLID&&/^[0-9]+$/.test(serialized)?{kind:Kind.INT,value:serialized}:{kind:Kind.STRING,value:JSON.stringify(serialized).slice(1,-1)};throw new TypeError("Cannot convert value to AST: "+String(serialized))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.astFromValue=astFromValue;var _iterall=require("iterall"),_invariant2=_interopRequireDefault(require("../jsutils/invariant")),_isNullish2=_interopRequireDefault(require("../jsutils/isNullish")),_isInvalid2=_interopRequireDefault(require("../jsutils/isInvalid")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_definition=require("../type/definition"),_scalars=require("../type/scalars")},{"../jsutils/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../language/kinds":102,"../type/definition":112,"../type/scalars":116,iterall:166}],121:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function buildWrappedType(innerType,inputTypeNode){if(inputTypeNode.kind===Kind.LIST_TYPE)return new _definition.GraphQLList(buildWrappedType(innerType,inputTypeNode.type));if(inputTypeNode.kind===Kind.NON_NULL_TYPE){var wrappedType=buildWrappedType(innerType,inputTypeNode.type);return(0,_invariant2.default)(!(wrappedType instanceof _definition.GraphQLNonNull),"No nesting nonnull."),new _definition.GraphQLNonNull(wrappedType)}return innerType}function getNamedTypeNode(typeNode){for(var namedType=typeNode;namedType.kind===Kind.LIST_TYPE||namedType.kind===Kind.NON_NULL_TYPE;)namedType=namedType.type;return namedType}function buildASTSchema(ast){function getObjectType(typeNode){var type=typeDefNamed(typeNode.name.value);return(0,_invariant2.default)(type instanceof _definition.GraphQLObjectType,"AST must provide object type."),type}function produceType(typeNode){return buildWrappedType(typeDefNamed(getNamedTypeNode(typeNode).name.value),typeNode)}function produceInputType(typeNode){return(0,_definition.assertInputType)(produceType(typeNode))}function produceOutputType(typeNode){return(0,_definition.assertOutputType)(produceType(typeNode))}function produceObjectType(typeNode){var type=produceType(typeNode);return(0,_invariant2.default)(type instanceof _definition.GraphQLObjectType,"Expected Object type."),type}function produceInterfaceType(typeNode){var type=produceType(typeNode);return(0,_invariant2.default)(type instanceof _definition.GraphQLInterfaceType,"Expected Interface type."),type}function typeDefNamed(typeName){if(innerTypeMap[typeName])return innerTypeMap[typeName];if(!nodeMap[typeName])throw new Error('Type "'+typeName+'" not found in document.');var innerTypeDef=makeSchemaDef(nodeMap[typeName]);if(!innerTypeDef)throw new Error('Nothing constructed for "'+typeName+'".');return innerTypeMap[typeName]=innerTypeDef,innerTypeDef}function makeSchemaDef(def){if(!def)throw new Error("def must be defined");switch(def.kind){case Kind.OBJECT_TYPE_DEFINITION:return makeTypeDef(def);case Kind.INTERFACE_TYPE_DEFINITION:return makeInterfaceDef(def);case Kind.ENUM_TYPE_DEFINITION:return makeEnumDef(def);case Kind.UNION_TYPE_DEFINITION:return makeUnionDef(def);case Kind.SCALAR_TYPE_DEFINITION:return makeScalarDef(def);case Kind.INPUT_OBJECT_TYPE_DEFINITION:return makeInputObjectDef(def);default:throw new Error('Type kind "'+def.kind+'" not supported.')}}function makeTypeDef(def){var typeName=def.name.value;return new _definition.GraphQLObjectType({name:typeName,description:getDescription(def),fields:function(){return makeFieldDefMap(def)},interfaces:function(){return makeImplementedInterfaces(def)}})}function makeFieldDefMap(def){return(0,_keyValMap2.default)(def.fields,function(field){return field.name.value},function(field){return{type:produceOutputType(field.type),description:getDescription(field),args:makeInputValues(field.arguments),deprecationReason:getDeprecationReason(field)}})}function makeImplementedInterfaces(def){return def.interfaces&&def.interfaces.map(function(iface){return produceInterfaceType(iface)})}function makeInputValues(values){return(0,_keyValMap2.default)(values,function(value){return value.name.value},function(value){var type=produceInputType(value.type);return{type:type,description:getDescription(value),defaultValue:(0,_valueFromAST.valueFromAST)(value.defaultValue,type)}})}function makeInterfaceDef(def){var typeName=def.name.value;return new _definition.GraphQLInterfaceType({name:typeName,description:getDescription(def),fields:function(){return makeFieldDefMap(def)},resolveType:cannotExecuteSchema})}function makeEnumDef(def){return new _definition.GraphQLEnumType({name:def.name.value,description:getDescription(def),values:(0,_keyValMap2.default)(def.values,function(enumValue){return enumValue.name.value},function(enumValue){return{description:getDescription(enumValue),deprecationReason:getDeprecationReason(enumValue)}})})}function makeUnionDef(def){return new _definition.GraphQLUnionType({name:def.name.value,description:getDescription(def),types:def.types.map(function(t){return produceObjectType(t)}),resolveType:cannotExecuteSchema})}function makeScalarDef(def){return new _definition.GraphQLScalarType({name:def.name.value,description:getDescription(def),serialize:function(){return null},parseValue:function(){return!1},parseLiteral:function(){return!1}})}function makeInputObjectDef(def){return new _definition.GraphQLInputObjectType({name:def.name.value,description:getDescription(def),fields:function(){return makeInputValues(def.fields)}})}if(!ast||ast.kind!==Kind.DOCUMENT)throw new Error("Must provide a document ast.");for(var schemaDef=void 0,typeDefs=[],nodeMap=Object.create(null),directiveDefs=[],i=0;i<ast.definitions.length;i++){var d=ast.definitions[i];switch(d.kind){case Kind.SCHEMA_DEFINITION:if(schemaDef)throw new Error("Must provide only one schema definition.");schemaDef=d;break;case Kind.SCALAR_TYPE_DEFINITION:case Kind.OBJECT_TYPE_DEFINITION:case Kind.INTERFACE_TYPE_DEFINITION:case Kind.ENUM_TYPE_DEFINITION:case Kind.UNION_TYPE_DEFINITION:case Kind.INPUT_OBJECT_TYPE_DEFINITION:var typeName=d.name.value;if(nodeMap[typeName])throw new Error('Type "'+typeName+'" was defined more than once.');typeDefs.push(d),nodeMap[typeName]=d;break;case Kind.DIRECTIVE_DEFINITION:directiveDefs.push(d)}}var queryTypeName=void 0,mutationTypeName=void 0,subscriptionTypeName=void 0;if(schemaDef?schemaDef.operationTypes.forEach(function(operationType){var typeName=operationType.type.name.value;if("query"===operationType.operation){if(queryTypeName)throw new Error("Must provide only one query type in schema.");if(!nodeMap[typeName])throw new Error('Specified query type "'+typeName+'" not found in document.');queryTypeName=typeName}else if("mutation"===operationType.operation){if(mutationTypeName)throw new Error("Must provide only one mutation type in schema.");if(!nodeMap[typeName])throw new Error('Specified mutation type "'+typeName+'" not found in document.');mutationTypeName=typeName}else if("subscription"===operationType.operation){if(subscriptionTypeName)throw new Error("Must provide only one subscription type in schema.");if(!nodeMap[typeName])throw new Error('Specified subscription type "'+typeName+'" not found in document.');subscriptionTypeName=typeName}}):(nodeMap.Query&&(queryTypeName="Query"),nodeMap.Mutation&&(mutationTypeName="Mutation"),nodeMap.Subscription&&(subscriptionTypeName="Subscription")),!queryTypeName)throw new Error("Must provide schema definition with query type or a type named Query.");var innerTypeMap={String:_scalars.GraphQLString,Int:_scalars.GraphQLInt,Float:_scalars.GraphQLFloat,Boolean:_scalars.GraphQLBoolean,ID:_scalars.GraphQLID,__Schema:_introspection.__Schema,__Directive:_introspection.__Directive,__DirectiveLocation:_introspection.__DirectiveLocation,__Type:_introspection.__Type,__Field:_introspection.__Field,__InputValue:_introspection.__InputValue,__EnumValue:_introspection.__EnumValue,__TypeKind:_introspection.__TypeKind},types=typeDefs.map(function(def){return typeDefNamed(def.name.value)}),directives=directiveDefs.map(function(directiveNode){return new _directives.GraphQLDirective({name:directiveNode.name.value,description:getDescription(directiveNode),locations:directiveNode.locations.map(function(node){return node.value}),args:directiveNode.arguments&&makeInputValues(directiveNode.arguments)})});return directives.some(function(directive){return"skip"===directive.name})||directives.push(_directives.GraphQLSkipDirective),directives.some(function(directive){return"include"===directive.name})||directives.push(_directives.GraphQLIncludeDirective),directives.some(function(directive){return"deprecated"===directive.name})||directives.push(_directives.GraphQLDeprecatedDirective),new _schema.GraphQLSchema({query:getObjectType(nodeMap[queryTypeName]),mutation:mutationTypeName?getObjectType(nodeMap[mutationTypeName]):null,subscription:subscriptionTypeName?getObjectType(nodeMap[subscriptionTypeName]):null,types:types,directives:directives})}function getDeprecationReason(node){var deprecated=(0,_values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective,node);return deprecated&&deprecated.reason}function getDescription(node){var loc=node.loc;if(loc){for(var comments=[],minSpaces=void 0,token=loc.startToken.prev;token&&token.kind===_lexer.TokenKind.COMMENT&&token.next&&token.prev&&token.line+1===token.next.line&&token.line!==token.prev.line;){var value=String(token.value),spaces=leadingSpaces(value);(void 0===minSpaces||spaces<minSpaces)&&(minSpaces=spaces),comments.push(value),token=token.prev}return comments.reverse().map(function(comment){return comment.slice(minSpaces)}).join("\n")}}function leadingSpaces(str){for(var i=0;i<str.length&&" "===str[i];i++);return i}function cannotExecuteSchema(){throw new Error("Generated Schema cannot use Interface or Union types for execution.")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildASTSchema=buildASTSchema,exports.getDeprecationReason=getDeprecationReason,exports.getDescription=getDescription,exports.buildSchema=function(source){return buildASTSchema((0,_parser.parse)(source))};var _invariant2=_interopRequireDefault(require("../jsutils/invariant")),_keyValMap2=_interopRequireDefault(require("../jsutils/keyValMap")),_valueFromAST=require("./valueFromAST"),_lexer=require("../language/lexer"),_parser=require("../language/parser"),_values=require("../execution/values"),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_schema=require("../type/schema"),_scalars=require("../type/scalars"),_definition=require("../type/definition"),_directives=require("../type/directives"),_introspection=require("../type/introspection")},{"../execution/values":90,"../jsutils/invariant":94,"../jsutils/keyValMap":98,"../language/kinds":102,"../language/lexer":103,"../language/parser":105,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/scalars":116,"../type/schema":117,"./valueFromAST":136}],122:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function cannotExecuteClientSchema(){throw new Error("Client Schema cannot use Interface or Union types for execution.")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildClientSchema=function(introspection){function getType(typeRef){if(typeRef.kind===_introspection.TypeKind.LIST){var itemRef=typeRef.ofType;if(!itemRef)throw new Error("Decorated type deeper than introspection query.");return new _definition.GraphQLList(getType(itemRef))}if(typeRef.kind===_introspection.TypeKind.NON_NULL){var nullableRef=typeRef.ofType;if(!nullableRef)throw new Error("Decorated type deeper than introspection query.");var nullableType=getType(nullableRef);return(0,_invariant2.default)(!(nullableType instanceof _definition.GraphQLNonNull),"No nesting nonnull."),new _definition.GraphQLNonNull(nullableType)}return getNamedType(typeRef.name)}function getNamedType(typeName){if(typeDefCache[typeName])return typeDefCache[typeName];var typeIntrospection=typeIntrospectionMap[typeName];if(!typeIntrospection)throw new Error("Invalid or incomplete schema, unknown type: "+typeName+". Ensure that a full introspection query is used in order to build a client schema.");var typeDef=buildType(typeIntrospection);return typeDefCache[typeName]=typeDef,typeDef}function getInputType(typeRef){var type=getType(typeRef);return(0,_invariant2.default)((0,_definition.isInputType)(type),"Introspection must provide input type for arguments."),type}function getOutputType(typeRef){var type=getType(typeRef);return(0,_invariant2.default)((0,_definition.isOutputType)(type),"Introspection must provide output type for fields."),type}function getObjectType(typeRef){var type=getType(typeRef);return(0,_invariant2.default)(type instanceof _definition.GraphQLObjectType,"Introspection must provide object type for possibleTypes."),type}function getInterfaceType(typeRef){var type=getType(typeRef);return(0,_invariant2.default)(type instanceof _definition.GraphQLInterfaceType,"Introspection must provide interface type for interfaces."),type}function buildType(type){switch(type.kind){case _introspection.TypeKind.SCALAR:return buildScalarDef(type);case _introspection.TypeKind.OBJECT:return buildObjectDef(type);case _introspection.TypeKind.INTERFACE:return buildInterfaceDef(type);case _introspection.TypeKind.UNION:return buildUnionDef(type);case _introspection.TypeKind.ENUM:return buildEnumDef(type);case _introspection.TypeKind.INPUT_OBJECT:return buildInputObjectDef(type);default:throw new Error("Invalid or incomplete schema, unknown kind: "+type.kind+". Ensure that a full introspection query is used in order to build a client schema.")}}function buildScalarDef(scalarIntrospection){return new _definition.GraphQLScalarType({name:scalarIntrospection.name,description:scalarIntrospection.description,serialize:function(id){return id},parseValue:function(){return!1},parseLiteral:function(){return!1}})}function buildObjectDef(objectIntrospection){return new _definition.GraphQLObjectType({name:objectIntrospection.name,description:objectIntrospection.description,interfaces:objectIntrospection.interfaces.map(getInterfaceType),fields:function(){return buildFieldDefMap(objectIntrospection)}})}function buildInterfaceDef(interfaceIntrospection){return new _definition.GraphQLInterfaceType({name:interfaceIntrospection.name,description:interfaceIntrospection.description,fields:function(){return buildFieldDefMap(interfaceIntrospection)},resolveType:cannotExecuteClientSchema})}function buildUnionDef(unionIntrospection){return new _definition.GraphQLUnionType({name:unionIntrospection.name,description:unionIntrospection.description,types:unionIntrospection.possibleTypes.map(getObjectType),resolveType:cannotExecuteClientSchema})}function buildEnumDef(enumIntrospection){return new _definition.GraphQLEnumType({name:enumIntrospection.name,description:enumIntrospection.description,values:(0,_keyValMap2.default)(enumIntrospection.enumValues,function(valueIntrospection){return valueIntrospection.name},function(valueIntrospection){return{description:valueIntrospection.description,deprecationReason:valueIntrospection.deprecationReason}})})}function buildInputObjectDef(inputObjectIntrospection){return new _definition.GraphQLInputObjectType({name:inputObjectIntrospection.name,description:inputObjectIntrospection.description,fields:function(){return buildInputValueDefMap(inputObjectIntrospection.inputFields)}})}function buildFieldDefMap(typeIntrospection){return(0,_keyValMap2.default)(typeIntrospection.fields,function(fieldIntrospection){return fieldIntrospection.name},function(fieldIntrospection){return{description:fieldIntrospection.description,deprecationReason:fieldIntrospection.deprecationReason,type:getOutputType(fieldIntrospection.type),args:buildInputValueDefMap(fieldIntrospection.args)}})}function buildInputValueDefMap(inputValueIntrospections){return(0,_keyValMap2.default)(inputValueIntrospections,function(inputValue){return inputValue.name},buildInputValue)}function buildInputValue(inputValueIntrospection){var type=getInputType(inputValueIntrospection.type),defaultValue=inputValueIntrospection.defaultValue?(0,_valueFromAST.valueFromAST)((0,_parser.parseValue)(inputValueIntrospection.defaultValue),type):void 0;return{name:inputValueIntrospection.name,description:inputValueIntrospection.description,type:type,defaultValue:defaultValue}}var schemaIntrospection=introspection.__schema,typeIntrospectionMap=(0,_keyMap2.default)(schemaIntrospection.types,function(type){return type.name}),typeDefCache={String:_scalars.GraphQLString,Int:_scalars.GraphQLInt,Float:_scalars.GraphQLFloat,Boolean:_scalars.GraphQLBoolean,ID:_scalars.GraphQLID,__Schema:_introspection.__Schema,__Directive:_introspection.__Directive,__DirectiveLocation:_introspection.__DirectiveLocation,__Type:_introspection.__Type,__Field:_introspection.__Field,__InputValue:_introspection.__InputValue,__EnumValue:_introspection.__EnumValue,__TypeKind:_introspection.__TypeKind},types=schemaIntrospection.types.map(function(typeIntrospection){return getNamedType(typeIntrospection.name)}),queryType=getObjectType(schemaIntrospection.queryType),mutationType=schemaIntrospection.mutationType?getObjectType(schemaIntrospection.mutationType):null,subscriptionType=schemaIntrospection.subscriptionType?getObjectType(schemaIntrospection.subscriptionType):null,directives=schemaIntrospection.directives?schemaIntrospection.directives.map(function(directiveIntrospection){var locations=directiveIntrospection.locations?directiveIntrospection.locations.slice():[].concat(directiveIntrospection.onField?[_directives.DirectiveLocation.FIELD]:[],directiveIntrospection.onOperation?[_directives.DirectiveLocation.QUERY,_directives.DirectiveLocation.MUTATION,_directives.DirectiveLocation.SUBSCRIPTION]:[],directiveIntrospection.onFragment?[_directives.DirectiveLocation.FRAGMENT_DEFINITION,_directives.DirectiveLocation.FRAGMENT_SPREAD,_directives.DirectiveLocation.INLINE_FRAGMENT]:[]);return new _directives.GraphQLDirective({name:directiveIntrospection.name,description:directiveIntrospection.description,locations:locations,args:buildInputValueDefMap(directiveIntrospection.args)})}):[];return new _schema.GraphQLSchema({query:queryType,mutation:mutationType,subscription:subscriptionType,types:types,directives:directives})};var _invariant2=_interopRequireDefault(require("../jsutils/invariant")),_keyMap2=_interopRequireDefault(require("../jsutils/keyMap")),_keyValMap2=_interopRequireDefault(require("../jsutils/keyValMap")),_valueFromAST=require("./valueFromAST"),_parser=require("../language/parser"),_schema=require("../type/schema"),_definition=require("../type/definition"),_introspection=require("../type/introspection"),_scalars=require("../type/scalars"),_directives=require("../type/directives")},{"../jsutils/invariant":94,"../jsutils/keyMap":97,"../jsutils/keyValMap":98,"../language/parser":105,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/scalars":116,"../type/schema":117,"./valueFromAST":136}],123:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.concatAST=function(asts){for(var batchDefinitions=[],i=0;i<asts.length;i++)for(var definitions=asts[i].definitions,j=0;j<definitions.length;j++)batchDefinitions.push(definitions[j]);return{kind:"Document",definitions:batchDefinitions}}},{}],124:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function cannotExecuteExtendedSchema(){throw new Error("Extended Schema cannot use Interface or Union types for execution.")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.extendSchema=function(schema,documentAST){function getTypeFromDef(typeDef){var type=_getNamedType(typeDef.name);return(0,_invariant2.default)(type,"Missing type from schema"),type}function getTypeFromAST(node){var type=_getNamedType(node.name.value);if(!type)throw new _GraphQLError.GraphQLError('Unknown type: "'+node.name.value+'". Ensure that this type exists either in the original schema, or is added in a type definition.',[node]);return type}function getObjectTypeFromAST(node){var type=getTypeFromAST(node);return(0,_invariant2.default)(type instanceof _definition.GraphQLObjectType,"Must be Object type."),type}function getInterfaceTypeFromAST(node){var type=getTypeFromAST(node);return(0,_invariant2.default)(type instanceof _definition.GraphQLInterfaceType,"Must be Interface type."),type}function getInputTypeFromAST(node){return(0,_definition.assertInputType)(getTypeFromAST(node))}function getOutputTypeFromAST(node){return(0,_definition.assertOutputType)(getTypeFromAST(node))}function _getNamedType(typeName){var cachedTypeDef=typeDefCache[typeName];if(cachedTypeDef)return cachedTypeDef;var existingType=schema.getType(typeName);if(existingType){var typeDef=extendType(existingType);return typeDefCache[typeName]=typeDef,typeDef}var typeNode=typeDefinitionMap[typeName];if(typeNode){var _typeDef=buildType(typeNode);return typeDefCache[typeName]=_typeDef,_typeDef}}function extendType(type){return type instanceof _definition.GraphQLObjectType?extendObjectType(type):type instanceof _definition.GraphQLInterfaceType?extendInterfaceType(type):type instanceof _definition.GraphQLUnionType?extendUnionType(type):type}function extendObjectType(type){return new _definition.GraphQLObjectType({name:type.name,description:type.description,interfaces:function(){return extendImplementedInterfaces(type)},fields:function(){return extendFieldMap(type)},isTypeOf:type.isTypeOf})}function extendInterfaceType(type){return new _definition.GraphQLInterfaceType({name:type.name,description:type.description,fields:function(){return extendFieldMap(type)},resolveType:type.resolveType})}function extendUnionType(type){return new _definition.GraphQLUnionType({name:type.name,description:type.description,types:type.getTypes().map(getTypeFromDef),resolveType:type.resolveType})}function extendImplementedInterfaces(type){var interfaces=type.getInterfaces().map(getTypeFromDef),extensions=typeExtensionsMap[type.name];return extensions&&extensions.forEach(function(extension){extension.definition.interfaces.forEach(function(namedType){var interfaceName=namedType.name.value;if(interfaces.some(function(def){return def.name===interfaceName}))throw new _GraphQLError.GraphQLError('Type "'+type.name+'" already implements "'+interfaceName+'". It cannot also be implemented in this type extension.',[namedType]);interfaces.push(getInterfaceTypeFromAST(namedType))})}),interfaces}function extendFieldMap(type){var newFieldMap=Object.create(null),oldFieldMap=type.getFields();Object.keys(oldFieldMap).forEach(function(fieldName){var field=oldFieldMap[fieldName];newFieldMap[fieldName]={description:field.description,deprecationReason:field.deprecationReason,type:extendFieldType(field.type),args:(0,_keyMap2.default)(field.args,function(arg){return arg.name}),resolve:field.resolve}});var extensions=typeExtensionsMap[type.name];return extensions&&extensions.forEach(function(extension){extension.definition.fields.forEach(function(field){var fieldName=field.name.value;if(oldFieldMap[fieldName])throw new _GraphQLError.GraphQLError('Field "'+type.name+"."+fieldName+'" already exists in the schema. It cannot also be defined in this type extension.',[field]);newFieldMap[fieldName]={description:(0,_buildASTSchema.getDescription)(field),type:buildOutputFieldType(field.type),args:buildInputValues(field.arguments),deprecationReason:(0,_buildASTSchema.getDeprecationReason)(field)}})}),newFieldMap}function extendFieldType(typeDef){return typeDef instanceof _definition.GraphQLList?new _definition.GraphQLList(extendFieldType(typeDef.ofType)):typeDef instanceof _definition.GraphQLNonNull?new _definition.GraphQLNonNull(extendFieldType(typeDef.ofType)):getTypeFromDef(typeDef)}function buildType(typeNode){switch(typeNode.kind){case Kind.OBJECT_TYPE_DEFINITION:return buildObjectType(typeNode);case Kind.INTERFACE_TYPE_DEFINITION:return buildInterfaceType(typeNode);case Kind.UNION_TYPE_DEFINITION:return buildUnionType(typeNode);case Kind.SCALAR_TYPE_DEFINITION:return buildScalarType(typeNode);case Kind.ENUM_TYPE_DEFINITION:return buildEnumType(typeNode);case Kind.INPUT_OBJECT_TYPE_DEFINITION:return buildInputObjectType(typeNode)}throw new TypeError("Unknown type kind "+typeNode.kind)}function buildObjectType(typeNode){return new _definition.GraphQLObjectType({name:typeNode.name.value,description:(0,_buildASTSchema.getDescription)(typeNode),interfaces:function(){return buildImplementedInterfaces(typeNode)},fields:function(){return buildFieldMap(typeNode)}})}function buildInterfaceType(typeNode){return new _definition.GraphQLInterfaceType({name:typeNode.name.value,description:(0,_buildASTSchema.getDescription)(typeNode),fields:function(){return buildFieldMap(typeNode)},resolveType:cannotExecuteExtendedSchema})}function buildUnionType(typeNode){return new _definition.GraphQLUnionType({name:typeNode.name.value,description:(0,_buildASTSchema.getDescription)(typeNode),types:typeNode.types.map(getObjectTypeFromAST),resolveType:cannotExecuteExtendedSchema})}function buildScalarType(typeNode){return new _definition.GraphQLScalarType({name:typeNode.name.value,description:(0,_buildASTSchema.getDescription)(typeNode),serialize:function(id){return id},parseValue:function(){return!1},parseLiteral:function(){return!1}})}function buildEnumType(typeNode){return new _definition.GraphQLEnumType({name:typeNode.name.value,description:(0,_buildASTSchema.getDescription)(typeNode),values:(0,_keyValMap2.default)(typeNode.values,function(enumValue){return enumValue.name.value},function(enumValue){return{description:(0,_buildASTSchema.getDescription)(enumValue),deprecationReason:(0,_buildASTSchema.getDeprecationReason)(enumValue)}})})}function buildInputObjectType(typeNode){return new _definition.GraphQLInputObjectType({name:typeNode.name.value,description:(0,_buildASTSchema.getDescription)(typeNode),fields:function(){return buildInputValues(typeNode.fields)}})}function getDirective(directiveNode){return new _directives.GraphQLDirective({name:directiveNode.name.value,locations:directiveNode.locations.map(function(node){return node.value}),args:directiveNode.arguments&&buildInputValues(directiveNode.arguments)})}function buildImplementedInterfaces(typeNode){return typeNode.interfaces&&typeNode.interfaces.map(getInterfaceTypeFromAST)}function buildFieldMap(typeNode){return(0,_keyValMap2.default)(typeNode.fields,function(field){return field.name.value},function(field){return{type:buildOutputFieldType(field.type),description:(0,_buildASTSchema.getDescription)(field),args:buildInputValues(field.arguments),deprecationReason:(0,_buildASTSchema.getDeprecationReason)(field)}})}function buildInputValues(values){return(0,_keyValMap2.default)(values,function(value){return value.name.value},function(value){var type=buildInputFieldType(value.type);return{type:type,description:(0,_buildASTSchema.getDescription)(value),defaultValue:(0,_valueFromAST.valueFromAST)(value.defaultValue,type)}})}function buildInputFieldType(typeNode){if(typeNode.kind===Kind.LIST_TYPE)return new _definition.GraphQLList(buildInputFieldType(typeNode.type));if(typeNode.kind===Kind.NON_NULL_TYPE){var nullableType=buildInputFieldType(typeNode.type);return(0,_invariant2.default)(!(nullableType instanceof _definition.GraphQLNonNull),"Must be nullable"),new _definition.GraphQLNonNull(nullableType)}return getInputTypeFromAST(typeNode)}function buildOutputFieldType(typeNode){if(typeNode.kind===Kind.LIST_TYPE)return new _definition.GraphQLList(buildOutputFieldType(typeNode.type));if(typeNode.kind===Kind.NON_NULL_TYPE){var nullableType=buildOutputFieldType(typeNode.type);return(0,_invariant2.default)(!(nullableType instanceof _definition.GraphQLNonNull),"Must be nullable"),new _definition.GraphQLNonNull(nullableType)}return getOutputTypeFromAST(typeNode)}(0,_invariant2.default)(schema instanceof _schema.GraphQLSchema,"Must provide valid GraphQLSchema"),(0,_invariant2.default)(documentAST&&documentAST.kind===Kind.DOCUMENT,"Must provide valid Document AST");for(var typeDefinitionMap=Object.create(null),typeExtensionsMap=Object.create(null),directiveDefinitions=[],i=0;i<documentAST.definitions.length;i++){var def=documentAST.definitions[i];switch(def.kind){case Kind.OBJECT_TYPE_DEFINITION:case Kind.INTERFACE_TYPE_DEFINITION:case Kind.ENUM_TYPE_DEFINITION:case Kind.UNION_TYPE_DEFINITION:case Kind.SCALAR_TYPE_DEFINITION:case Kind.INPUT_OBJECT_TYPE_DEFINITION:var typeName=def.name.value;if(schema.getType(typeName))throw new _GraphQLError.GraphQLError('Type "'+typeName+'" already exists in the schema. It cannot also be defined in this type definition.',[def]);typeDefinitionMap[typeName]=def;break;case Kind.TYPE_EXTENSION_DEFINITION:var extendedTypeName=def.definition.name.value,existingType=schema.getType(extendedTypeName);if(!existingType)throw new _GraphQLError.GraphQLError('Cannot extend type "'+extendedTypeName+'" because it does not exist in the existing schema.',[def.definition]);if(!(existingType instanceof _definition.GraphQLObjectType))throw new _GraphQLError.GraphQLError('Cannot extend non-object type "'+extendedTypeName+'".',[def.definition]);var extensions=typeExtensionsMap[extendedTypeName];extensions?extensions.push(def):extensions=[def],typeExtensionsMap[extendedTypeName]=extensions;break;case Kind.DIRECTIVE_DEFINITION:var directiveName=def.name.value;if(schema.getDirective(directiveName))throw new _GraphQLError.GraphQLError('Directive "'+directiveName+'" already exists in the schema. It cannot be redefined.',[def]);directiveDefinitions.push(def)}}if(0===Object.keys(typeExtensionsMap).length&&0===Object.keys(typeDefinitionMap).length&&0===directiveDefinitions.length)return schema;var typeDefCache={String:_scalars.GraphQLString,Int:_scalars.GraphQLInt,Float:_scalars.GraphQLFloat,Boolean:_scalars.GraphQLBoolean,ID:_scalars.GraphQLID,__Schema:_introspection.__Schema,__Directive:_introspection.__Directive,__DirectiveLocation:_introspection.__DirectiveLocation,__Type:_introspection.__Type,__Field:_introspection.__Field,__InputValue:_introspection.__InputValue,__EnumValue:_introspection.__EnumValue,__TypeKind:_introspection.__TypeKind},queryType=getTypeFromDef(schema.getQueryType()),existingMutationType=schema.getMutationType(),mutationType=existingMutationType?getTypeFromDef(existingMutationType):null,existingSubscriptionType=schema.getSubscriptionType(),subscriptionType=existingSubscriptionType?getTypeFromDef(existingSubscriptionType):null,typeMap=schema.getTypeMap(),types=Object.keys(typeMap).map(function(typeName){return getTypeFromDef(typeMap[typeName])});return Object.keys(typeDefinitionMap).forEach(function(typeName){types.push(getTypeFromAST(typeDefinitionMap[typeName]))}),new _schema.GraphQLSchema({query:queryType,mutation:mutationType,subscription:subscriptionType,types:types,directives:function(){var existingDirectives=schema.getDirectives();(0,_invariant2.default)(existingDirectives,"schema must have default directives");var newDirectives=directiveDefinitions.map(function(directiveNode){return getDirective(directiveNode)});return existingDirectives.concat(newDirectives)}()})};var _invariant2=_interopRequireDefault(require("../jsutils/invariant")),_keyMap2=_interopRequireDefault(require("../jsutils/keyMap")),_keyValMap2=_interopRequireDefault(require("../jsutils/keyValMap")),_buildASTSchema=require("./buildASTSchema"),_valueFromAST=require("./valueFromAST"),_GraphQLError=require("../error/GraphQLError"),_schema=require("../type/schema"),_definition=require("../type/definition"),_directives=require("../type/directives"),_introspection=require("../type/introspection"),_scalars=require("../type/scalars"),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds"))},{"../error/GraphQLError":83,"../jsutils/invariant":94,"../jsutils/keyMap":97,"../jsutils/keyValMap":98,"../language/kinds":102,"../type/definition":112,"../type/directives":113,"../type/introspection":115,"../type/scalars":116,"../type/schema":117,"./buildASTSchema":121,"./valueFromAST":136}],125:[function(require,module,exports){"use strict";function findRemovedTypes(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),breakingChanges=[];return Object.keys(oldTypeMap).forEach(function(typeName){newTypeMap[typeName]||breakingChanges.push({type:BreakingChangeType.TYPE_REMOVED,description:typeName+" was removed."})}),breakingChanges}function findTypesThatChangedKind(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),breakingChanges=[];return Object.keys(oldTypeMap).forEach(function(typeName){if(newTypeMap[typeName]){var oldType=oldTypeMap[typeName],newType=newTypeMap[typeName];oldType instanceof newType.constructor||breakingChanges.push({type:BreakingChangeType.TYPE_CHANGED_KIND,description:typeName+" changed from "+typeKindName(oldType)+" to "+typeKindName(newType)+"."})}}),breakingChanges}function findArgChanges(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),breakingChanges=[],dangerousChanges=[];return Object.keys(oldTypeMap).forEach(function(typeName){var oldType=oldTypeMap[typeName],newType=newTypeMap[typeName];if((oldType instanceof _definition.GraphQLObjectType||oldType instanceof _definition.GraphQLInterfaceType)&&newType instanceof oldType.constructor){var oldTypeFields=oldType.getFields(),newTypeFields=newType.getFields();Object.keys(oldTypeFields).forEach(function(fieldName){newTypeFields[fieldName]&&(oldTypeFields[fieldName].args.forEach(function(oldArgDef){var newArgDef=newTypeFields[fieldName].args.find(function(arg){return arg.name===oldArgDef.name});newArgDef?isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type,newArgDef.type)?void 0!==oldArgDef.defaultValue&&oldArgDef.defaultValue!==newArgDef.defaultValue&&dangerousChanges.push({type:DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,description:oldType.name+"."+fieldName+" arg "+oldArgDef.name+" has changed defaultValue"}):breakingChanges.push({type:BreakingChangeType.ARG_CHANGED_KIND,description:oldType.name+"."+fieldName+" arg "+oldArgDef.name+" has changed type from "+oldArgDef.type.toString()+" to "+newArgDef.type.toString()}):breakingChanges.push({type:BreakingChangeType.ARG_REMOVED,description:oldType.name+"."+fieldName+" arg "+oldArgDef.name+" was removed"})}),newTypeFields[fieldName].args.forEach(function(newArgDef){!oldTypeFields[fieldName].args.find(function(arg){return arg.name===newArgDef.name})&&newArgDef.type instanceof _definition.GraphQLNonNull&&breakingChanges.push({type:BreakingChangeType.NON_NULL_ARG_ADDED,description:"A non-null arg "+newArgDef.name+" on "+newType.name+"."+fieldName+" was added"})}))})}}),{breakingChanges:breakingChanges,dangerousChanges:dangerousChanges}}function typeKindName(type){if(type instanceof _definition.GraphQLScalarType)return"a Scalar type";if(type instanceof _definition.GraphQLObjectType)return"an Object type";if(type instanceof _definition.GraphQLInterfaceType)return"an Interface type";if(type instanceof _definition.GraphQLUnionType)return"a Union type";if(type instanceof _definition.GraphQLEnumType)return"an Enum type";if(type instanceof _definition.GraphQLInputObjectType)return"an Input type";throw new TypeError("Unknown type "+type.constructor.name)}function findFieldsThatChangedType(oldSchema,newSchema){return[].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema,newSchema),findFieldsThatChangedTypeOnInputObjectTypes(oldSchema,newSchema))}function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),breakingFieldChanges=[];return Object.keys(oldTypeMap).forEach(function(typeName){var oldType=oldTypeMap[typeName],newType=newTypeMap[typeName];if((oldType instanceof _definition.GraphQLObjectType||oldType instanceof _definition.GraphQLInterfaceType)&&newType instanceof oldType.constructor){var oldTypeFieldsDef=oldType.getFields(),newTypeFieldsDef=newType.getFields();Object.keys(oldTypeFieldsDef).forEach(function(fieldName){if(fieldName in newTypeFieldsDef){var oldFieldType=oldTypeFieldsDef[fieldName].type,newFieldType=newTypeFieldsDef[fieldName].type;if(!isChangeSafeForObjectOrInterfaceField(oldFieldType,newFieldType)){var oldFieldTypeString=(0,_definition.isNamedType)(oldFieldType)?oldFieldType.name:oldFieldType.toString(),newFieldTypeString=(0,_definition.isNamedType)(newFieldType)?newFieldType.name:newFieldType.toString();breakingFieldChanges.push({type:BreakingChangeType.FIELD_CHANGED_KIND,description:typeName+"."+fieldName+" changed type from "+oldFieldTypeString+" to "+newFieldTypeString+"."})}}else breakingFieldChanges.push({type:BreakingChangeType.FIELD_REMOVED,description:typeName+"."+fieldName+" was removed."})})}}),breakingFieldChanges}function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),breakingFieldChanges=[];return Object.keys(oldTypeMap).forEach(function(typeName){var oldType=oldTypeMap[typeName],newType=newTypeMap[typeName];if(oldType instanceof _definition.GraphQLInputObjectType&&newType instanceof _definition.GraphQLInputObjectType){var oldTypeFieldsDef=oldType.getFields(),newTypeFieldsDef=newType.getFields();Object.keys(oldTypeFieldsDef).forEach(function(fieldName){if(fieldName in newTypeFieldsDef){var oldFieldType=oldTypeFieldsDef[fieldName].type,newFieldType=newTypeFieldsDef[fieldName].type;if(!isChangeSafeForInputObjectFieldOrFieldArg(oldFieldType,newFieldType)){var oldFieldTypeString=(0,_definition.isNamedType)(oldFieldType)?oldFieldType.name:oldFieldType.toString(),newFieldTypeString=(0,_definition.isNamedType)(newFieldType)?newFieldType.name:newFieldType.toString();breakingFieldChanges.push({type:BreakingChangeType.FIELD_CHANGED_KIND,description:typeName+"."+fieldName+" changed type from "+oldFieldTypeString+" to "+newFieldTypeString+"."})}}else breakingFieldChanges.push({type:BreakingChangeType.FIELD_REMOVED,description:typeName+"."+fieldName+" was removed."})}),Object.keys(newTypeFieldsDef).forEach(function(fieldName){!(fieldName in oldTypeFieldsDef)&&newTypeFieldsDef[fieldName].type instanceof _definition.GraphQLNonNull&&breakingFieldChanges.push({type:BreakingChangeType.NON_NULL_INPUT_FIELD_ADDED,description:"A non-null field "+fieldName+" on input type "+newType.name+" was added."})})}}),breakingFieldChanges}function isChangeSafeForObjectOrInterfaceField(oldType,newType){return(0,_definition.isNamedType)(oldType)?(0,_definition.isNamedType)(newType)&&oldType.name===newType.name||newType instanceof _definition.GraphQLNonNull&&isChangeSafeForObjectOrInterfaceField(oldType,newType.ofType):oldType instanceof _definition.GraphQLList?newType instanceof _definition.GraphQLList&&isChangeSafeForObjectOrInterfaceField(oldType.ofType,newType.ofType)||newType instanceof _definition.GraphQLNonNull&&isChangeSafeForObjectOrInterfaceField(oldType,newType.ofType):oldType instanceof _definition.GraphQLNonNull&&(newType instanceof _definition.GraphQLNonNull&&isChangeSafeForObjectOrInterfaceField(oldType.ofType,newType.ofType))}function isChangeSafeForInputObjectFieldOrFieldArg(oldType,newType){return(0,_definition.isNamedType)(oldType)?(0,_definition.isNamedType)(newType)&&oldType.name===newType.name:oldType instanceof _definition.GraphQLList?newType instanceof _definition.GraphQLList&&isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType,newType.ofType):oldType instanceof _definition.GraphQLNonNull&&(newType instanceof _definition.GraphQLNonNull&&isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType,newType.ofType)||!(newType instanceof _definition.GraphQLNonNull)&&isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType,newType))}function findTypesRemovedFromUnions(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),typesRemovedFromUnion=[];return Object.keys(oldTypeMap).forEach(function(typeName){var oldType=oldTypeMap[typeName],newType=newTypeMap[typeName];if(oldType instanceof _definition.GraphQLUnionType&&newType instanceof _definition.GraphQLUnionType){var typeNamesInNewUnion=Object.create(null);newType.getTypes().forEach(function(type){typeNamesInNewUnion[type.name]=!0}),oldType.getTypes().forEach(function(type){typeNamesInNewUnion[type.name]||typesRemovedFromUnion.push({type:BreakingChangeType.TYPE_REMOVED_FROM_UNION,description:type.name+" was removed from union type "+typeName+"."})})}}),typesRemovedFromUnion}function findValuesRemovedFromEnums(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),valuesRemovedFromEnums=[];return Object.keys(oldTypeMap).forEach(function(typeName){var oldType=oldTypeMap[typeName],newType=newTypeMap[typeName];if(oldType instanceof _definition.GraphQLEnumType&&newType instanceof _definition.GraphQLEnumType){var valuesInNewEnum=Object.create(null);newType.getValues().forEach(function(value){valuesInNewEnum[value.name]=!0}),oldType.getValues().forEach(function(value){valuesInNewEnum[value.name]||valuesRemovedFromEnums.push({type:BreakingChangeType.VALUE_REMOVED_FROM_ENUM,description:value.name+" was removed from enum type "+typeName+"."})})}}),valuesRemovedFromEnums}function findInterfacesRemovedFromObjectTypes(oldSchema,newSchema){var oldTypeMap=oldSchema.getTypeMap(),newTypeMap=newSchema.getTypeMap(),breakingChanges=[];return Object.keys(oldTypeMap).forEach(function(typeName){var oldType=oldTypeMap[typeName],newType=newTypeMap[typeName];if(oldType instanceof _definition.GraphQLObjectType&&newType instanceof _definition.GraphQLObjectType){var oldInterfaces=oldType.getInterfaces(),newInterfaces=newType.getInterfaces();oldInterfaces.forEach(function(oldInterface){newInterfaces.some(function(int){return int.name===oldInterface.name})||breakingChanges.push({type:BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT,description:typeName+" no longer implements interface "+oldInterface.name+"."})})}}),breakingChanges}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DangerousChangeType=exports.BreakingChangeType=void 0,exports.findBreakingChanges=function(oldSchema,newSchema){return[].concat(findRemovedTypes(oldSchema,newSchema),findTypesThatChangedKind(oldSchema,newSchema),findFieldsThatChangedType(oldSchema,newSchema),findTypesRemovedFromUnions(oldSchema,newSchema),findValuesRemovedFromEnums(oldSchema,newSchema),findArgChanges(oldSchema,newSchema).breakingChanges,findInterfacesRemovedFromObjectTypes(oldSchema,newSchema))},exports.findDangerousChanges=function(oldSchema,newSchema){return[].concat(findArgChanges(oldSchema,newSchema).dangerousChanges)},exports.findRemovedTypes=findRemovedTypes,exports.findTypesThatChangedKind=findTypesThatChangedKind,exports.findArgChanges=findArgChanges,exports.findFieldsThatChangedType=findFieldsThatChangedType,exports.findFieldsThatChangedTypeOnInputObjectTypes=findFieldsThatChangedTypeOnInputObjectTypes,exports.findTypesRemovedFromUnions=findTypesRemovedFromUnions,exports.findValuesRemovedFromEnums=findValuesRemovedFromEnums,exports.findInterfacesRemovedFromObjectTypes=findInterfacesRemovedFromObjectTypes;var _definition=require("../type/definition"),BreakingChangeType=(require("../type/schema"),exports.BreakingChangeType={FIELD_CHANGED_KIND:"FIELD_CHANGED_KIND",FIELD_REMOVED:"FIELD_REMOVED",TYPE_CHANGED_KIND:"TYPE_CHANGED_KIND",TYPE_REMOVED:"TYPE_REMOVED",TYPE_REMOVED_FROM_UNION:"TYPE_REMOVED_FROM_UNION",VALUE_REMOVED_FROM_ENUM:"VALUE_REMOVED_FROM_ENUM",ARG_REMOVED:"ARG_REMOVED",ARG_CHANGED_KIND:"ARG_CHANGED_KIND",NON_NULL_ARG_ADDED:"NON_NULL_ARG_ADDED",NON_NULL_INPUT_FIELD_ADDED:"NON_NULL_INPUT_FIELD_ADDED",INTERFACE_REMOVED_FROM_OBJECT:"INTERFACE_REMOVED_FROM_OBJECT"}),DangerousChangeType=exports.DangerousChangeType={ARG_DEFAULT_VALUE_CHANGE:"ARG_DEFAULT_VALUE_CHANGE"}},{"../type/definition":112,"../type/schema":117}],126:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.findDeprecatedUsages=function(schema,ast){var errors=[],typeInfo=new _TypeInfo.TypeInfo(schema);return(0,_visitor.visit)(ast,(0,_visitor.visitWithTypeInfo)(typeInfo,{Field:function(node){var fieldDef=typeInfo.getFieldDef();if(fieldDef&&fieldDef.isDeprecated){var parentType=typeInfo.getParentType();if(parentType){var reason=fieldDef.deprecationReason;errors.push(new _GraphQLError.GraphQLError("The field "+parentType.name+"."+fieldDef.name+" is deprecated."+(reason?" "+reason:""),[node]))}}},EnumValue:function(node){var enumVal=typeInfo.getEnumValue();if(enumVal&&enumVal.isDeprecated){var type=(0,_definition.getNamedType)(typeInfo.getInputType());if(type){var reason=enumVal.deprecationReason;errors.push(new _GraphQLError.GraphQLError("The enum value "+type.name+"."+enumVal.name+" is deprecated."+(reason?" "+reason:""),[node]))}}}})),errors};var _GraphQLError=require("../error/GraphQLError"),_visitor=require("../language/visitor"),_definition=require("../type/definition"),_TypeInfo=(require("../type/schema"),require("./TypeInfo"))},{"../error/GraphQLError":83,"../language/visitor":108,"../type/definition":112,"../type/schema":117,"./TypeInfo":118}],127:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOperationAST=function(documentAST,operationName){for(var operation=null,i=0;i<documentAST.definitions.length;i++){var definition=documentAST.definitions[i];if(definition.kind===_kinds.OPERATION_DEFINITION)if(operationName){if(definition.name&&definition.name.value===operationName)return definition}else{if(operation)return null;operation=definition}}return operation};var _kinds=require("../language/kinds")},{"../language/kinds":102}],128:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _introspectionQuery=require("./introspectionQuery");Object.defineProperty(exports,"introspectionQuery",{enumerable:!0,get:function(){return _introspectionQuery.introspectionQuery}});var _getOperationAST=require("./getOperationAST");Object.defineProperty(exports,"getOperationAST",{enumerable:!0,get:function(){return _getOperationAST.getOperationAST}});var _buildClientSchema=require("./buildClientSchema");Object.defineProperty(exports,"buildClientSchema",{enumerable:!0,get:function(){return _buildClientSchema.buildClientSchema}});var _buildASTSchema=require("./buildASTSchema");Object.defineProperty(exports,"buildASTSchema",{enumerable:!0,get:function(){return _buildASTSchema.buildASTSchema}}),Object.defineProperty(exports,"buildSchema",{enumerable:!0,get:function(){return _buildASTSchema.buildSchema}});var _extendSchema=require("./extendSchema");Object.defineProperty(exports,"extendSchema",{enumerable:!0,get:function(){return _extendSchema.extendSchema}});var _schemaPrinter=require("./schemaPrinter");Object.defineProperty(exports,"printSchema",{enumerable:!0,get:function(){return _schemaPrinter.printSchema}}),Object.defineProperty(exports,"printType",{enumerable:!0,get:function(){return _schemaPrinter.printType}}),Object.defineProperty(exports,"printIntrospectionSchema",{enumerable:!0,get:function(){return _schemaPrinter.printIntrospectionSchema}});var _typeFromAST=require("./typeFromAST");Object.defineProperty(exports,"typeFromAST",{enumerable:!0,get:function(){return _typeFromAST.typeFromAST}});var _valueFromAST=require("./valueFromAST");Object.defineProperty(exports,"valueFromAST",{enumerable:!0,get:function(){return _valueFromAST.valueFromAST}});var _astFromValue=require("./astFromValue");Object.defineProperty(exports,"astFromValue",{enumerable:!0,get:function(){return _astFromValue.astFromValue}});var _TypeInfo=require("./TypeInfo");Object.defineProperty(exports,"TypeInfo",{enumerable:!0,get:function(){return _TypeInfo.TypeInfo}});var _isValidJSValue=require("./isValidJSValue");Object.defineProperty(exports,"isValidJSValue",{enumerable:!0,get:function(){return _isValidJSValue.isValidJSValue}});var _isValidLiteralValue=require("./isValidLiteralValue");Object.defineProperty(exports,"isValidLiteralValue",{enumerable:!0,get:function(){return _isValidLiteralValue.isValidLiteralValue}});var _concatAST=require("./concatAST");Object.defineProperty(exports,"concatAST",{enumerable:!0,get:function(){return _concatAST.concatAST}});var _separateOperations=require("./separateOperations");Object.defineProperty(exports,"separateOperations",{enumerable:!0,get:function(){return _separateOperations.separateOperations}});var _typeComparators=require("./typeComparators");Object.defineProperty(exports,"isEqualType",{enumerable:!0,get:function(){return _typeComparators.isEqualType}}),Object.defineProperty(exports,"isTypeSubTypeOf",{enumerable:!0,get:function(){return _typeComparators.isTypeSubTypeOf}}),Object.defineProperty(exports,"doTypesOverlap",{enumerable:!0,get:function(){return _typeComparators.doTypesOverlap}});var _assertValidName=require("./assertValidName");Object.defineProperty(exports,"assertValidName",{enumerable:!0,get:function(){return _assertValidName.assertValidName}});var _findBreakingChanges=require("./findBreakingChanges");Object.defineProperty(exports,"BreakingChangeType",{enumerable:!0,get:function(){return _findBreakingChanges.BreakingChangeType}}),Object.defineProperty(exports,"DangerousChangeType",{enumerable:!0,get:function(){return _findBreakingChanges.DangerousChangeType}}),Object.defineProperty(exports,"findBreakingChanges",{enumerable:!0,get:function(){return _findBreakingChanges.findBreakingChanges}});var _findDeprecatedUsages=require("./findDeprecatedUsages");Object.defineProperty(exports,"findDeprecatedUsages",{enumerable:!0,get:function(){return _findDeprecatedUsages.findDeprecatedUsages}})},{"./TypeInfo":118,"./assertValidName":119,"./astFromValue":120,"./buildASTSchema":121,"./buildClientSchema":122,"./concatAST":123,"./extendSchema":124,"./findBreakingChanges":125,"./findDeprecatedUsages":126,"./getOperationAST":127,"./introspectionQuery":129,"./isValidJSValue":130,"./isValidLiteralValue":131,"./schemaPrinter":132,"./separateOperations":133,"./typeComparators":134,"./typeFromAST":135,"./valueFromAST":136}],129:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.introspectionQuery="\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n"},{}],130:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function isValidJSValue(value,type){if(type instanceof _definition.GraphQLNonNull)return(0,_isNullish2.default)(value)?['Expected "'+String(type)+'", found null.']:isValidJSValue(value,type.ofType);if((0,_isNullish2.default)(value))return[];if(type instanceof _definition.GraphQLList){var itemType=type.ofType;if((0,_iterall.isCollection)(value)){var errors=[];return(0,_iterall.forEach)(value,function(item,index){errors.push.apply(errors,isValidJSValue(item,itemType).map(function(error){return"In element #"+index+": "+error}))}),errors}return isValidJSValue(value,itemType)}if(type instanceof _definition.GraphQLInputObjectType){if("object"!=typeof value||null===value)return['Expected "'+type.name+'", found not an object.'];var fields=type.getFields(),_errors=[];return Object.keys(value).forEach(function(providedField){fields[providedField]||_errors.push('In field "'+providedField+'": Unknown field.')}),Object.keys(fields).forEach(function(fieldName){var newErrors=isValidJSValue(value[fieldName],fields[fieldName].type);_errors.push.apply(_errors,newErrors.map(function(error){return'In field "'+fieldName+'": '+error}))}),_errors}(0,_invariant2.default)(type instanceof _definition.GraphQLScalarType||type instanceof _definition.GraphQLEnumType,"Must be input type");try{var parseResult=type.parseValue(value);if((0,_isNullish2.default)(parseResult)&&!type.isValidValue(value))return['Expected type "'+type.name+'", found '+JSON.stringify(value)+"."]}catch(error){return['Expected type "'+type.name+'", found '+JSON.stringify(value)+": "+error.message]}return[]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.isValidJSValue=isValidJSValue;var _iterall=require("iterall"),_invariant2=_interopRequireDefault(require("../jsutils/invariant")),_isNullish2=_interopRequireDefault(require("../jsutils/isNullish")),_definition=require("../type/definition")},{"../jsutils/invariant":94,"../jsutils/isNullish":96,"../type/definition":112,iterall:166}],131:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function isValidLiteralValue(type,valueNode){if(type instanceof _definition.GraphQLNonNull)return valueNode&&valueNode.kind!==Kind.NULL?isValidLiteralValue(type.ofType,valueNode):['Expected "'+String(type)+'", found null.'];if(!valueNode||valueNode.kind===Kind.NULL)return[];if(valueNode.kind===Kind.VARIABLE)return[];if(type instanceof _definition.GraphQLList){var itemType=type.ofType;return valueNode.kind===Kind.LIST?valueNode.values.reduce(function(acc,item,index){var errors=isValidLiteralValue(itemType,item);return acc.concat(errors.map(function(error){return"In element #"+index+": "+error}))},[]):isValidLiteralValue(itemType,valueNode)}if(type instanceof _definition.GraphQLInputObjectType){if(valueNode.kind!==Kind.OBJECT)return['Expected "'+type.name+'", found not an object.'];var fields=type.getFields(),errors=[],fieldNodes=valueNode.fields;fieldNodes.forEach(function(providedFieldNode){fields[providedFieldNode.name.value]||errors.push('In field "'+providedFieldNode.name.value+'": Unknown field.')});var fieldNodeMap=(0,_keyMap2.default)(fieldNodes,function(fieldNode){return fieldNode.name.value});return Object.keys(fields).forEach(function(fieldName){var result=isValidLiteralValue(fields[fieldName].type,fieldNodeMap[fieldName]&&fieldNodeMap[fieldName].value);errors.push.apply(errors,result.map(function(error){return'In field "'+fieldName+'": '+error}))}),errors}return(0,_invariant2.default)(type instanceof _definition.GraphQLScalarType||type instanceof _definition.GraphQLEnumType,"Must be input type"),type.isValidLiteral(valueNode)?[]:['Expected type "'+type.name+'", found '+(0,_printer.print)(valueNode)+"."]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.isValidLiteralValue=isValidLiteralValue;var _printer=require("../language/printer"),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_definition=require("../type/definition"),_invariant2=_interopRequireDefault(require("../jsutils/invariant")),_keyMap2=_interopRequireDefault(require("../jsutils/keyMap"))},{"../jsutils/invariant":94,"../jsutils/keyMap":97,"../language/kinds":102,"../language/printer":106,"../type/definition":112}],132:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function isSpecDirective(directiveName){return"skip"===directiveName||"include"===directiveName||"deprecated"===directiveName}function isDefinedType(typename){return!isIntrospectionType(typename)&&!isBuiltInScalar(typename)}function isIntrospectionType(typename){return 0===typename.indexOf("__")}function isBuiltInScalar(typename){return"String"===typename||"Boolean"===typename||"Int"===typename||"Float"===typename||"ID"===typename}function printFilteredSchema(schema,directiveFilter,typeFilter){var directives=schema.getDirectives().filter(function(directive){return directiveFilter(directive.name)}),typeMap=schema.getTypeMap(),types=Object.keys(typeMap).filter(typeFilter).sort(function(name1,name2){return name1.localeCompare(name2)}).map(function(typeName){return typeMap[typeName]});return[printSchemaDefinition(schema)].concat(directives.map(printDirective),types.map(printType)).filter(Boolean).join("\n\n")+"\n"}function printSchemaDefinition(schema){if(!isSchemaOfCommonNames(schema)){var operationTypes=[],queryType=schema.getQueryType();queryType&&operationTypes.push(" query: "+queryType.name);var mutationType=schema.getMutationType();mutationType&&operationTypes.push(" mutation: "+mutationType.name);var subscriptionType=schema.getSubscriptionType();return subscriptionType&&operationTypes.push(" subscription: "+subscriptionType.name),"schema {\n"+operationTypes.join("\n")+"\n}"}}function isSchemaOfCommonNames(schema){var queryType=schema.getQueryType();if(queryType&&"Query"!==queryType.name)return!1;var mutationType=schema.getMutationType();if(mutationType&&"Mutation"!==mutationType.name)return!1;var subscriptionType=schema.getSubscriptionType();return!subscriptionType||"Subscription"===subscriptionType.name}function printType(type){return type instanceof _definition.GraphQLScalarType?printScalar(type):type instanceof _definition.GraphQLObjectType?printObject(type):type instanceof _definition.GraphQLInterfaceType?printInterface(type):type instanceof _definition.GraphQLUnionType?printUnion(type):type instanceof _definition.GraphQLEnumType?printEnum(type):((0,_invariant2.default)(type instanceof _definition.GraphQLInputObjectType),printInputObject(type))}function printScalar(type){return printDescription(type)+"scalar "+type.name}function printObject(type){var interfaces=type.getInterfaces(),implementedInterfaces=interfaces.length?" implements "+interfaces.map(function(i){return i.name}).join(", "):"";return printDescription(type)+"type "+type.name+implementedInterfaces+" {\n"+printFields(type)+"\n}"}function printInterface(type){return printDescription(type)+"interface "+type.name+" {\n"+printFields(type)+"\n}"}function printUnion(type){return printDescription(type)+"union "+type.name+" = "+type.getTypes().join(" | ")}function printEnum(type){return printDescription(type)+"enum "+type.name+" {\n"+printEnumValues(type.getValues())+"\n}"}function printEnumValues(values){return values.map(function(value,i){return printDescription(value," ",!i)+" "+value.name+printDeprecated(value)}).join("\n")}function printInputObject(type){var fieldMap=type.getFields(),fields=Object.keys(fieldMap).map(function(fieldName){return fieldMap[fieldName]});return printDescription(type)+"input "+type.name+" {\n"+fields.map(function(f,i){return printDescription(f," ",!i)+" "+printInputValue(f)}).join("\n")+"\n}"}function printFields(type){var fieldMap=type.getFields();return Object.keys(fieldMap).map(function(fieldName){return fieldMap[fieldName]}).map(function(f,i){return printDescription(f," ",!i)+" "+f.name+printArgs(f.args," ")+": "+String(f.type)+printDeprecated(f)}).join("\n")}function printArgs(args){var indentation=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return 0===args.length?"":args.every(function(arg){return!arg.description})?"("+args.map(printInputValue).join(", ")+")":"(\n"+args.map(function(arg,i){return printDescription(arg," "+indentation,!i)+" "+indentation+printInputValue(arg)}).join("\n")+"\n"+indentation+")"}function printInputValue(arg){var argDecl=arg.name+": "+String(arg.type);return(0,_isInvalid2.default)(arg.defaultValue)||(argDecl+=" = "+(0,_printer.print)((0,_astFromValue.astFromValue)(arg.defaultValue,arg.type))),argDecl}function printDirective(directive){return printDescription(directive)+"directive @"+directive.name+printArgs(directive.args)+" on "+directive.locations.join(" | ")}function printDeprecated(fieldOrEnumVal){var reason=fieldOrEnumVal.deprecationReason;return(0,_isNullish2.default)(reason)?"":""===reason||reason===_directives.DEFAULT_DEPRECATION_REASON?" @deprecated":" @deprecated(reason: "+(0,_printer.print)((0,_astFromValue.astFromValue)(reason,_scalars.GraphQLString))+")"}function printDescription(def){var indentation=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",firstInBlock=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!def.description)return"";for(var lines=def.description.split("\n"),description=indentation&&!firstInBlock?"\n":"",i=0;i<lines.length;i++)if(""===lines[i])description+=indentation+"#\n";else for(var sublines=breakLine(lines[i],120-indentation.length),j=0;j<sublines.length;j++)description+=indentation+"# "+sublines[j]+"\n";return description}function breakLine(line,len){if(line.length<len+5)return[line];var parts=line.split(new RegExp("((?: |^).{15,"+(len-40)+"}(?= |$))"));if(parts.length<4)return[line];for(var sublines=[parts[0]+parts[1]+parts[2]],i=3;i<parts.length;i+=2)sublines.push(parts[i].slice(1)+parts[i+1]);return sublines}Object.defineProperty(exports,"__esModule",{value:!0}),exports.printSchema=function(schema){return printFilteredSchema(schema,function(n){return!isSpecDirective(n)},isDefinedType)},exports.printIntrospectionSchema=function(schema){return printFilteredSchema(schema,isSpecDirective,isIntrospectionType)},exports.printType=printType;var _invariant2=_interopRequireDefault(require("../jsutils/invariant")),_isNullish2=_interopRequireDefault(require("../jsutils/isNullish")),_isInvalid2=_interopRequireDefault(require("../jsutils/isInvalid")),_astFromValue=require("../utilities/astFromValue"),_printer=require("../language/printer"),_definition=require("../type/definition"),_scalars=require("../type/scalars"),_directives=require("../type/directives")},{"../jsutils/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../language/printer":106,"../type/definition":112,"../type/directives":113,"../type/scalars":116,"../utilities/astFromValue":120}],133:[function(require,module,exports){"use strict";function opName(operation){return operation.name?operation.name.value:""}function collectTransitiveDependencies(collected,depGraph,fromName){var immediateDeps=depGraph[fromName];immediateDeps&&Object.keys(immediateDeps).forEach(function(toName){collected[toName]||(collected[toName]=!0,collectTransitiveDependencies(collected,depGraph,toName))})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.separateOperations=function(documentAST){var operations=[],fragments=Object.create(null),positions=new Map,depGraph=Object.create(null),fromName=void 0,idx=0;(0,_visitor.visit)(documentAST,{OperationDefinition:function(node){fromName=opName(node),operations.push(node),positions.set(node,idx++)},FragmentDefinition:function(node){fromName=node.name.value,fragments[fromName]=node,positions.set(node,idx++)},FragmentSpread:function(node){var toName=node.name.value;(depGraph[fromName]||(depGraph[fromName]=Object.create(null)))[toName]=!0}});var separatedDocumentASTs=Object.create(null);return operations.forEach(function(operation){var operationName=opName(operation),dependencies=Object.create(null);collectTransitiveDependencies(dependencies,depGraph,operationName);var definitions=[operation];Object.keys(dependencies).forEach(function(name){definitions.push(fragments[name])}),definitions.sort(function(n1,n2){return(positions.get(n1)||0)-(positions.get(n2)||0)}),separatedDocumentASTs[operationName]={kind:"Document",definitions:definitions}}),separatedDocumentASTs};var _visitor=require("../language/visitor")},{"../language/visitor":108}],134:[function(require,module,exports){"use strict";function isEqualType(typeA,typeB){return typeA===typeB||(typeA instanceof _definition.GraphQLNonNull&&typeB instanceof _definition.GraphQLNonNull?isEqualType(typeA.ofType,typeB.ofType):typeA instanceof _definition.GraphQLList&&typeB instanceof _definition.GraphQLList&&isEqualType(typeA.ofType,typeB.ofType))}function isTypeSubTypeOf(schema,maybeSubType,superType){return maybeSubType===superType||(superType instanceof _definition.GraphQLNonNull?maybeSubType instanceof _definition.GraphQLNonNull&&isTypeSubTypeOf(schema,maybeSubType.ofType,superType.ofType):maybeSubType instanceof _definition.GraphQLNonNull?isTypeSubTypeOf(schema,maybeSubType.ofType,superType):superType instanceof _definition.GraphQLList?maybeSubType instanceof _definition.GraphQLList&&isTypeSubTypeOf(schema,maybeSubType.ofType,superType.ofType):!(maybeSubType instanceof _definition.GraphQLList)&&!!((0,_definition.isAbstractType)(superType)&&maybeSubType instanceof _definition.GraphQLObjectType&&schema.isPossibleType(superType,maybeSubType)))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.isEqualType=isEqualType,exports.isTypeSubTypeOf=isTypeSubTypeOf,exports.doTypesOverlap=function(schema,typeA,typeB){var _typeB=typeB;return typeA===_typeB||((0,_definition.isAbstractType)(typeA)?(0,_definition.isAbstractType)(_typeB)?schema.getPossibleTypes(typeA).some(function(type){return schema.isPossibleType(_typeB,type)}):schema.isPossibleType(typeA,_typeB):!!(0,_definition.isAbstractType)(_typeB)&&schema.isPossibleType(_typeB,typeA))};var _definition=require("../type/definition")},{"../type/definition":112}],135:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.typeFromAST=void 0;var _invariant2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../jsutils/invariant")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_definition=require("../type/definition"),typeFromAST=exports.typeFromAST=function(schema,typeNode){var innerType=void 0;return typeNode.kind===Kind.LIST_TYPE?(innerType=typeFromAST(schema,typeNode.type))&&new _definition.GraphQLList(innerType):typeNode.kind===Kind.NON_NULL_TYPE?(innerType=typeFromAST(schema,typeNode.type))&&new _definition.GraphQLNonNull(innerType):((0,_invariant2.default)(typeNode.kind===Kind.NAMED_TYPE,"Must be a named type."),schema.getType(typeNode.name.value))}},{"../jsutils/invariant":94,"../language/kinds":102,"../type/definition":112}],136:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function valueFromAST(valueNode,type,variables){if(valueNode){if(type instanceof _definition.GraphQLNonNull){if(valueNode.kind===Kind.NULL)return;return valueFromAST(valueNode,type.ofType,variables)}if(valueNode.kind===Kind.NULL)return null;if(valueNode.kind===Kind.VARIABLE){var variableName=valueNode.name.value;if(!variables||(0,_isInvalid2.default)(variables[variableName]))return;return variables[variableName]}if(type instanceof _definition.GraphQLList){var itemType=type.ofType;if(valueNode.kind===Kind.LIST){for(var coercedValues=[],itemNodes=valueNode.values,i=0;i<itemNodes.length;i++)if(isMissingVariable(itemNodes[i],variables)){if(itemType instanceof _definition.GraphQLNonNull)return;coercedValues.push(null)}else{var itemValue=valueFromAST(itemNodes[i],itemType,variables);if((0,_isInvalid2.default)(itemValue))return;coercedValues.push(itemValue)}return coercedValues}var coercedValue=valueFromAST(valueNode,itemType,variables);if((0,_isInvalid2.default)(coercedValue))return;return[coercedValue]}if(type instanceof _definition.GraphQLInputObjectType){if(valueNode.kind!==Kind.OBJECT)return;for(var coercedObj=Object.create(null),fields=type.getFields(),fieldNodes=(0,_keyMap2.default)(valueNode.fields,function(field){return field.name.value}),fieldNames=Object.keys(fields),_i=0;_i<fieldNames.length;_i++){var fieldName=fieldNames[_i],field=fields[fieldName],fieldNode=fieldNodes[fieldName];if(fieldNode&&!isMissingVariable(fieldNode.value,variables)){var fieldValue=valueFromAST(fieldNode.value,field.type,variables);if((0,_isInvalid2.default)(fieldValue))return;coercedObj[fieldName]=fieldValue}else if((0,_isInvalid2.default)(field.defaultValue)){if(field.type instanceof _definition.GraphQLNonNull)return}else coercedObj[fieldName]=field.defaultValue}return coercedObj}(0,_invariant2.default)(type instanceof _definition.GraphQLScalarType||type instanceof _definition.GraphQLEnumType,"Must be input type");var parsed=type.parseLiteral(valueNode);if(!(0,_isNullish2.default)(parsed)||type.isValidLiteral(valueNode))return parsed}}function isMissingVariable(valueNode,variables){return valueNode.kind===Kind.VARIABLE&&(!variables||(0,_isInvalid2.default)(variables[valueNode.name.value]))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.valueFromAST=valueFromAST;var _keyMap2=_interopRequireDefault(require("../jsutils/keyMap")),_invariant2=_interopRequireDefault(require("../jsutils/invariant")),_isNullish2=_interopRequireDefault(require("../jsutils/isNullish")),_isInvalid2=_interopRequireDefault(require("../jsutils/isInvalid")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_definition=require("../type/definition")},{"../jsutils/invariant":94,"../jsutils/isInvalid":95,"../jsutils/isNullish":96,"../jsutils/keyMap":97,"../language/kinds":102,"../type/definition":112}],137:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _validate=require("./validate");Object.defineProperty(exports,"validate",{enumerable:!0,get:function(){return _validate.validate}}),Object.defineProperty(exports,"ValidationContext",{enumerable:!0,get:function(){return _validate.ValidationContext}});var _specifiedRules=require("./specifiedRules");Object.defineProperty(exports,"specifiedRules",{enumerable:!0,get:function(){return _specifiedRules.specifiedRules}});var _ArgumentsOfCorrectType=require("./rules/ArgumentsOfCorrectType");Object.defineProperty(exports,"ArgumentsOfCorrectTypeRule",{enumerable:!0,get:function(){return _ArgumentsOfCorrectType.ArgumentsOfCorrectType}});var _DefaultValuesOfCorrectType=require("./rules/DefaultValuesOfCorrectType");Object.defineProperty(exports,"DefaultValuesOfCorrectTypeRule",{enumerable:!0,get:function(){return _DefaultValuesOfCorrectType.DefaultValuesOfCorrectType}});var _FieldsOnCorrectType=require("./rules/FieldsOnCorrectType");Object.defineProperty(exports,"FieldsOnCorrectTypeRule",{enumerable:!0,get:function(){return _FieldsOnCorrectType.FieldsOnCorrectType}});var _FragmentsOnCompositeTypes=require("./rules/FragmentsOnCompositeTypes");Object.defineProperty(exports,"FragmentsOnCompositeTypesRule",{enumerable:!0,get:function(){return _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes}});var _KnownArgumentNames=require("./rules/KnownArgumentNames");Object.defineProperty(exports,"KnownArgumentNamesRule",{enumerable:!0,get:function(){return _KnownArgumentNames.KnownArgumentNames}});var _KnownDirectives=require("./rules/KnownDirectives");Object.defineProperty(exports,"KnownDirectivesRule",{enumerable:!0,get:function(){return _KnownDirectives.KnownDirectives}});var _KnownFragmentNames=require("./rules/KnownFragmentNames");Object.defineProperty(exports,"KnownFragmentNamesRule",{enumerable:!0,get:function(){return _KnownFragmentNames.KnownFragmentNames}});var _KnownTypeNames=require("./rules/KnownTypeNames");Object.defineProperty(exports,"KnownTypeNamesRule",{enumerable:!0,get:function(){return _KnownTypeNames.KnownTypeNames}});var _LoneAnonymousOperation=require("./rules/LoneAnonymousOperation");Object.defineProperty(exports,"LoneAnonymousOperationRule",{enumerable:!0,get:function(){return _LoneAnonymousOperation.LoneAnonymousOperation}});var _NoFragmentCycles=require("./rules/NoFragmentCycles");Object.defineProperty(exports,"NoFragmentCyclesRule",{enumerable:!0,get:function(){return _NoFragmentCycles.NoFragmentCycles}});var _NoUndefinedVariables=require("./rules/NoUndefinedVariables");Object.defineProperty(exports,"NoUndefinedVariablesRule",{enumerable:!0,get:function(){return _NoUndefinedVariables.NoUndefinedVariables}});var _NoUnusedFragments=require("./rules/NoUnusedFragments");Object.defineProperty(exports,"NoUnusedFragmentsRule",{enumerable:!0,get:function(){return _NoUnusedFragments.NoUnusedFragments}});var _NoUnusedVariables=require("./rules/NoUnusedVariables");Object.defineProperty(exports,"NoUnusedVariablesRule",{enumerable:!0,get:function(){return _NoUnusedVariables.NoUnusedVariables}});var _OverlappingFieldsCanBeMerged=require("./rules/OverlappingFieldsCanBeMerged");Object.defineProperty(exports,"OverlappingFieldsCanBeMergedRule",{enumerable:!0,get:function(){return _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged}});var _PossibleFragmentSpreads=require("./rules/PossibleFragmentSpreads");Object.defineProperty(exports,"PossibleFragmentSpreadsRule",{enumerable:!0,get:function(){return _PossibleFragmentSpreads.PossibleFragmentSpreads}});var _ProvidedNonNullArguments=require("./rules/ProvidedNonNullArguments");Object.defineProperty(exports,"ProvidedNonNullArgumentsRule",{enumerable:!0,get:function(){return _ProvidedNonNullArguments.ProvidedNonNullArguments}});var _ScalarLeafs=require("./rules/ScalarLeafs");Object.defineProperty(exports,"ScalarLeafsRule",{enumerable:!0,get:function(){return _ScalarLeafs.ScalarLeafs}});var _SingleFieldSubscriptions=require("./rules/SingleFieldSubscriptions");Object.defineProperty(exports,"SingleFieldSubscriptionsRule",{enumerable:!0,get:function(){return _SingleFieldSubscriptions.SingleFieldSubscriptions}});var _UniqueArgumentNames=require("./rules/UniqueArgumentNames");Object.defineProperty(exports,"UniqueArgumentNamesRule",{enumerable:!0,get:function(){return _UniqueArgumentNames.UniqueArgumentNames}});var _UniqueDirectivesPerLocation=require("./rules/UniqueDirectivesPerLocation");Object.defineProperty(exports,"UniqueDirectivesPerLocationRule",{enumerable:!0,get:function(){return _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation}});var _UniqueFragmentNames=require("./rules/UniqueFragmentNames");Object.defineProperty(exports,"UniqueFragmentNamesRule",{enumerable:!0,get:function(){return _UniqueFragmentNames.UniqueFragmentNames}});var _UniqueInputFieldNames=require("./rules/UniqueInputFieldNames");Object.defineProperty(exports,"UniqueInputFieldNamesRule",{enumerable:!0,get:function(){return _UniqueInputFieldNames.UniqueInputFieldNames}});var _UniqueOperationNames=require("./rules/UniqueOperationNames");Object.defineProperty(exports,"UniqueOperationNamesRule",{enumerable:!0,get:function(){return _UniqueOperationNames.UniqueOperationNames}});var _UniqueVariableNames=require("./rules/UniqueVariableNames");Object.defineProperty(exports,"UniqueVariableNamesRule",{enumerable:!0,get:function(){return _UniqueVariableNames.UniqueVariableNames}});var _VariablesAreInputTypes=require("./rules/VariablesAreInputTypes");Object.defineProperty(exports,"VariablesAreInputTypesRule",{enumerable:!0,get:function(){return _VariablesAreInputTypes.VariablesAreInputTypes}});var _VariablesInAllowedPosition=require("./rules/VariablesInAllowedPosition");Object.defineProperty(exports,"VariablesInAllowedPositionRule",{enumerable:!0,get:function(){return _VariablesInAllowedPosition.VariablesInAllowedPosition}})},{"./rules/ArgumentsOfCorrectType":138,"./rules/DefaultValuesOfCorrectType":139,"./rules/FieldsOnCorrectType":140,"./rules/FragmentsOnCompositeTypes":141,"./rules/KnownArgumentNames":142,"./rules/KnownDirectives":143,"./rules/KnownFragmentNames":144,"./rules/KnownTypeNames":145,"./rules/LoneAnonymousOperation":146,"./rules/NoFragmentCycles":147,"./rules/NoUndefinedVariables":148,"./rules/NoUnusedFragments":149,"./rules/NoUnusedVariables":150,"./rules/OverlappingFieldsCanBeMerged":151,"./rules/PossibleFragmentSpreads":152,"./rules/ProvidedNonNullArguments":153,"./rules/ScalarLeafs":154,"./rules/SingleFieldSubscriptions":155,"./rules/UniqueArgumentNames":156,"./rules/UniqueDirectivesPerLocation":157,"./rules/UniqueFragmentNames":158,"./rules/UniqueInputFieldNames":159,"./rules/UniqueOperationNames":160,"./rules/UniqueVariableNames":161,"./rules/VariablesAreInputTypes":162,"./rules/VariablesInAllowedPosition":163,"./specifiedRules":164,"./validate":165}],138:[function(require,module,exports){"use strict";function badValueMessage(argName,type,value,verboseErrors){return'Argument "'+argName+'" has invalid value '+value+"."+(verboseErrors?"\n"+verboseErrors.join("\n"):"")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.badValueMessage=badValueMessage,exports.ArgumentsOfCorrectType=function(context){return{Argument:function(node){var argDef=context.getArgument();if(argDef){var errors=(0,_isValidLiteralValue.isValidLiteralValue)(argDef.type,node.value);errors&&errors.length>0&&context.reportError(new _error.GraphQLError(badValueMessage(node.name.value,argDef.type,(0,_printer.print)(node.value),errors),[node.value]))}return!1}}};var _error=require("../../error"),_printer=require("../../language/printer"),_isValidLiteralValue=require("../../utilities/isValidLiteralValue")},{"../../error":85,"../../language/printer":106,"../../utilities/isValidLiteralValue":131}],139:[function(require,module,exports){"use strict";function defaultForNonNullArgMessage(varName,type,guessType){return'Variable "$'+varName+'" of type "'+String(type)+'" is required and will not use the default value. Perhaps you meant to use type "'+String(guessType)+'".'}function badValueForDefaultArgMessage(varName,type,value,verboseErrors){var message=verboseErrors?"\n"+verboseErrors.join("\n"):"";return'Variable "$'+varName+'" of type "'+String(type)+'" has invalid default value '+value+"."+message}Object.defineProperty(exports,"__esModule",{value:!0}),exports.defaultForNonNullArgMessage=defaultForNonNullArgMessage,exports.badValueForDefaultArgMessage=badValueForDefaultArgMessage,exports.DefaultValuesOfCorrectType=function(context){return{VariableDefinition:function(node){var name=node.variable.name.value,defaultValue=node.defaultValue,type=context.getInputType();if(type instanceof _definition.GraphQLNonNull&&defaultValue&&context.reportError(new _error.GraphQLError(defaultForNonNullArgMessage(name,type,type.ofType),[defaultValue])),type&&defaultValue){var errors=(0,_isValidLiteralValue.isValidLiteralValue)(type,defaultValue);errors&&errors.length>0&&context.reportError(new _error.GraphQLError(badValueForDefaultArgMessage(name,type,(0,_printer.print)(defaultValue),errors),[defaultValue]))}return!1},SelectionSet:function(){return!1},FragmentDefinition:function(){return!1}}};var _error=require("../../error"),_printer=require("../../language/printer"),_definition=require("../../type/definition"),_isValidLiteralValue=require("../../utilities/isValidLiteralValue")},{"../../error":85,"../../language/printer":106,"../../type/definition":112,"../../utilities/isValidLiteralValue":131}],140:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function undefinedFieldMessage(fieldName,type,suggestedTypeNames,suggestedFieldNames){var message='Cannot query field "'+fieldName+'" on type "'+type+'".';return 0!==suggestedTypeNames.length?message+=" Did you mean to use an inline fragment on "+(0,_quotedOrList2.default)(suggestedTypeNames)+"?":0!==suggestedFieldNames.length&&(message+=" Did you mean "+(0,_quotedOrList2.default)(suggestedFieldNames)+"?"),message}function getSuggestedTypeNames(schema,type,fieldName){if((0,_definition.isAbstractType)(type)){var suggestedObjectTypes=[],interfaceUsageCount=Object.create(null);return schema.getPossibleTypes(type).forEach(function(possibleType){possibleType.getFields()[fieldName]&&(suggestedObjectTypes.push(possibleType.name),possibleType.getInterfaces().forEach(function(possibleInterface){possibleInterface.getFields()[fieldName]&&(interfaceUsageCount[possibleInterface.name]=(interfaceUsageCount[possibleInterface.name]||0)+1)}))}),Object.keys(interfaceUsageCount).sort(function(a,b){return interfaceUsageCount[b]-interfaceUsageCount[a]}).concat(suggestedObjectTypes)}return[]}function getSuggestedFieldNames(schema,type,fieldName){if(type instanceof _definition.GraphQLObjectType||type instanceof _definition.GraphQLInterfaceType){var possibleFieldNames=Object.keys(type.getFields());return(0,_suggestionList2.default)(fieldName,possibleFieldNames)}return[]}Object.defineProperty(exports,"__esModule",{value:!0}),exports.undefinedFieldMessage=undefinedFieldMessage,exports.FieldsOnCorrectType=function(context){return{Field:function(node){var type=context.getParentType();if(type&&!context.getFieldDef()){var schema=context.getSchema(),fieldName=node.name.value,suggestedTypeNames=getSuggestedTypeNames(schema,type,fieldName),suggestedFieldNames=0!==suggestedTypeNames.length?[]:getSuggestedFieldNames(0,type,fieldName);context.reportError(new _error.GraphQLError(undefinedFieldMessage(fieldName,type.name,suggestedTypeNames,suggestedFieldNames),[node]))}}}};var _error=require("../../error"),_suggestionList2=_interopRequireDefault(require("../../jsutils/suggestionList")),_quotedOrList2=_interopRequireDefault(require("../../jsutils/quotedOrList")),_definition=require("../../type/definition")},{"../../error":85,"../../jsutils/quotedOrList":99,"../../jsutils/suggestionList":100,"../../type/definition":112}],141:[function(require,module,exports){"use strict";function inlineFragmentOnNonCompositeErrorMessage(type){return'Fragment cannot condition on non composite type "'+String(type)+'".'}function fragmentOnNonCompositeErrorMessage(fragName,type){return'Fragment "'+fragName+'" cannot condition on non composite type "'+String(type)+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.inlineFragmentOnNonCompositeErrorMessage=inlineFragmentOnNonCompositeErrorMessage,exports.fragmentOnNonCompositeErrorMessage=fragmentOnNonCompositeErrorMessage,exports.FragmentsOnCompositeTypes=function(context){return{InlineFragment:function(node){if(node.typeCondition){var type=(0,_typeFromAST.typeFromAST)(context.getSchema(),node.typeCondition);type&&!(0,_definition.isCompositeType)(type)&&context.reportError(new _error.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0,_printer.print)(node.typeCondition)),[node.typeCondition]))}},FragmentDefinition:function(node){var type=(0,_typeFromAST.typeFromAST)(context.getSchema(),node.typeCondition);type&&!(0,_definition.isCompositeType)(type)&&context.reportError(new _error.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value,(0,_printer.print)(node.typeCondition)),[node.typeCondition]))}}};var _error=require("../../error"),_printer=require("../../language/printer"),_definition=require("../../type/definition"),_typeFromAST=require("../../utilities/typeFromAST")},{"../../error":85,"../../language/printer":106,"../../type/definition":112,"../../utilities/typeFromAST":135}],142:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function unknownArgMessage(argName,fieldName,type,suggestedArgs){var message='Unknown argument "'+argName+'" on field "'+fieldName+'" of type "'+String(type)+'".';return suggestedArgs.length&&(message+=" Did you mean "+(0,_quotedOrList2.default)(suggestedArgs)+"?"),message}function unknownDirectiveArgMessage(argName,directiveName,suggestedArgs){var message='Unknown argument "'+argName+'" on directive "@'+directiveName+'".';return suggestedArgs.length&&(message+=" Did you mean "+(0,_quotedOrList2.default)(suggestedArgs)+"?"),message}Object.defineProperty(exports,"__esModule",{value:!0}),exports.unknownArgMessage=unknownArgMessage,exports.unknownDirectiveArgMessage=unknownDirectiveArgMessage,exports.KnownArgumentNames=function(context){return{Argument:function(node,key,parent,path,ancestors){var argumentOf=ancestors[ancestors.length-1];if(argumentOf.kind===Kind.FIELD){var fieldDef=context.getFieldDef();if(fieldDef&&!(0,_find2.default)(fieldDef.args,function(arg){return arg.name===node.name.value})){var parentType=context.getParentType();(0,_invariant2.default)(parentType),context.reportError(new _error.GraphQLError(unknownArgMessage(node.name.value,fieldDef.name,parentType.name,(0,_suggestionList2.default)(node.name.value,fieldDef.args.map(function(arg){return arg.name}))),[node]))}}else if(argumentOf.kind===Kind.DIRECTIVE){var directive=context.getDirective();directive&&((0,_find2.default)(directive.args,function(arg){return arg.name===node.name.value})||context.reportError(new _error.GraphQLError(unknownDirectiveArgMessage(node.name.value,directive.name,(0,_suggestionList2.default)(node.name.value,directive.args.map(function(arg){return arg.name}))),[node])))}}}};var _error=require("../../error"),_find2=_interopRequireDefault(require("../../jsutils/find")),_invariant2=_interopRequireDefault(require("../../jsutils/invariant")),_suggestionList2=_interopRequireDefault(require("../../jsutils/suggestionList")),_quotedOrList2=_interopRequireDefault(require("../../jsutils/quotedOrList")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../../language/kinds"))},{"../../error":85,"../../jsutils/find":93,"../../jsutils/invariant":94,"../../jsutils/quotedOrList":99,"../../jsutils/suggestionList":100,"../../language/kinds":102}],143:[function(require,module,exports){"use strict";function unknownDirectiveMessage(directiveName){return'Unknown directive "'+directiveName+'".'}function misplacedDirectiveMessage(directiveName,location){return'Directive "'+directiveName+'" may not be used on '+location+"."}function getDirectiveLocationForASTPath(ancestors){var appliedTo=ancestors[ancestors.length-1];switch(appliedTo.kind){case Kind.OPERATION_DEFINITION:switch(appliedTo.operation){case"query":return _directives.DirectiveLocation.QUERY;case"mutation":return _directives.DirectiveLocation.MUTATION;case"subscription":return _directives.DirectiveLocation.SUBSCRIPTION}break;case Kind.FIELD:return _directives.DirectiveLocation.FIELD;case Kind.FRAGMENT_SPREAD:return _directives.DirectiveLocation.FRAGMENT_SPREAD;case Kind.INLINE_FRAGMENT:return _directives.DirectiveLocation.INLINE_FRAGMENT;case Kind.FRAGMENT_DEFINITION:return _directives.DirectiveLocation.FRAGMENT_DEFINITION;case Kind.SCHEMA_DEFINITION:return _directives.DirectiveLocation.SCHEMA;case Kind.SCALAR_TYPE_DEFINITION:return _directives.DirectiveLocation.SCALAR;case Kind.OBJECT_TYPE_DEFINITION:return _directives.DirectiveLocation.OBJECT;case Kind.FIELD_DEFINITION:return _directives.DirectiveLocation.FIELD_DEFINITION;case Kind.INTERFACE_TYPE_DEFINITION:return _directives.DirectiveLocation.INTERFACE;case Kind.UNION_TYPE_DEFINITION:return _directives.DirectiveLocation.UNION;case Kind.ENUM_TYPE_DEFINITION:return _directives.DirectiveLocation.ENUM;case Kind.ENUM_VALUE_DEFINITION:return _directives.DirectiveLocation.ENUM_VALUE;case Kind.INPUT_OBJECT_TYPE_DEFINITION:return _directives.DirectiveLocation.INPUT_OBJECT;case Kind.INPUT_VALUE_DEFINITION:return ancestors[ancestors.length-3].kind===Kind.INPUT_OBJECT_TYPE_DEFINITION?_directives.DirectiveLocation.INPUT_FIELD_DEFINITION:_directives.DirectiveLocation.ARGUMENT_DEFINITION}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.unknownDirectiveMessage=unknownDirectiveMessage,exports.misplacedDirectiveMessage=misplacedDirectiveMessage,exports.KnownDirectives=function(context){return{Directive:function(node,key,parent,path,ancestors){var directiveDef=(0,_find2.default)(context.getSchema().getDirectives(),function(def){return def.name===node.name.value});if(directiveDef){var candidateLocation=getDirectiveLocationForASTPath(ancestors);candidateLocation?-1===directiveDef.locations.indexOf(candidateLocation)&&context.reportError(new _error.GraphQLError(misplacedDirectiveMessage(node.name.value,candidateLocation),[node])):context.reportError(new _error.GraphQLError(misplacedDirectiveMessage(node.name.value,node.type),[node]))}else context.reportError(new _error.GraphQLError(unknownDirectiveMessage(node.name.value),[node]))}}};var _error=require("../../error"),_find2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../../jsutils/find")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../../language/kinds")),_directives=require("../../type/directives")},{"../../error":85,"../../jsutils/find":93,"../../language/kinds":102,"../../type/directives":113}],144:[function(require,module,exports){"use strict";function unknownFragmentMessage(fragName){return'Unknown fragment "'+fragName+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.unknownFragmentMessage=unknownFragmentMessage,exports.KnownFragmentNames=function(context){return{FragmentSpread:function(node){var fragmentName=node.name.value;context.getFragment(fragmentName)||context.reportError(new _error.GraphQLError(unknownFragmentMessage(fragmentName),[node.name]))}}};var _error=require("../../error")},{"../../error":85}],145:[function(require,module,exports){"use strict";function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function unknownTypeMessage(type,suggestedTypes){var message='Unknown type "'+String(type)+'".';return suggestedTypes.length&&(message+=" Did you mean "+(0,_quotedOrList2.default)(suggestedTypes)+"?"),message}Object.defineProperty(exports,"__esModule",{value:!0}),exports.unknownTypeMessage=unknownTypeMessage,exports.KnownTypeNames=function(context){return{ObjectTypeDefinition:function(){return!1},InterfaceTypeDefinition:function(){return!1},UnionTypeDefinition:function(){return!1},InputObjectTypeDefinition:function(){return!1},NamedType:function(node){var schema=context.getSchema(),typeName=node.name.value;schema.getType(typeName)||context.reportError(new _error.GraphQLError(unknownTypeMessage(typeName,(0,_suggestionList2.default)(typeName,Object.keys(schema.getTypeMap()))),[node]))}}};var _error=require("../../error"),_suggestionList2=_interopRequireDefault(require("../../jsutils/suggestionList")),_quotedOrList2=_interopRequireDefault(require("../../jsutils/quotedOrList"))},{"../../error":85,"../../jsutils/quotedOrList":99,"../../jsutils/suggestionList":100}],146:[function(require,module,exports){"use strict";function anonOperationNotAloneMessage(){return"This anonymous operation must be the only defined operation."}Object.defineProperty(exports,"__esModule",{value:!0}),exports.anonOperationNotAloneMessage=anonOperationNotAloneMessage,exports.LoneAnonymousOperation=function(context){var operationCount=0;return{Document:function(node){operationCount=node.definitions.filter(function(definition){return definition.kind===_kinds.OPERATION_DEFINITION}).length},OperationDefinition:function(node){!node.name&&operationCount>1&&context.reportError(new _error.GraphQLError(anonOperationNotAloneMessage(),[node]))}}};var _error=require("../../error"),_kinds=require("../../language/kinds")},{"../../error":85,"../../language/kinds":102}],147:[function(require,module,exports){"use strict";function cycleErrorMessage(fragName,spreadNames){return'Cannot spread fragment "'+fragName+'" within itself'+(spreadNames.length?" via "+spreadNames.join(", "):"")+"."}Object.defineProperty(exports,"__esModule",{value:!0}),exports.cycleErrorMessage=cycleErrorMessage,exports.NoFragmentCycles=function(context){function detectCycleRecursive(fragment){var fragmentName=fragment.name.value;visitedFrags[fragmentName]=!0;var spreadNodes=context.getFragmentSpreads(fragment.selectionSet);if(0!==spreadNodes.length){spreadPathIndexByName[fragmentName]=spreadPath.length;for(var i=0;i<spreadNodes.length;i++){var spreadNode=spreadNodes[i],spreadName=spreadNode.name.value,cycleIndex=spreadPathIndexByName[spreadName];if(void 0===cycleIndex){if(spreadPath.push(spreadNode),!visitedFrags[spreadName]){var spreadFragment=context.getFragment(spreadName);spreadFragment&&detectCycleRecursive(spreadFragment)}spreadPath.pop()}else{var cyclePath=spreadPath.slice(cycleIndex);context.reportError(new _error.GraphQLError(cycleErrorMessage(spreadName,cyclePath.map(function(s){return s.name.value})),cyclePath.concat(spreadNode)))}}spreadPathIndexByName[fragmentName]=void 0}}var visitedFrags=Object.create(null),spreadPath=[],spreadPathIndexByName=Object.create(null);return{OperationDefinition:function(){return!1},FragmentDefinition:function(node){return visitedFrags[node.name.value]||detectCycleRecursive(node),!1}}};var _error=require("../../error")},{"../../error":85}],148:[function(require,module,exports){"use strict";function undefinedVarMessage(varName,opName){return opName?'Variable "$'+varName+'" is not defined by operation "'+opName+'".':'Variable "$'+varName+'" is not defined.'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.undefinedVarMessage=undefinedVarMessage,exports.NoUndefinedVariables=function(context){var variableNameDefined=Object.create(null);return{OperationDefinition:{enter:function(){variableNameDefined=Object.create(null)},leave:function(operation){context.getRecursiveVariableUsages(operation).forEach(function(_ref){var node=_ref.node,varName=node.name.value;!0!==variableNameDefined[varName]&&context.reportError(new _error.GraphQLError(undefinedVarMessage(varName,operation.name&&operation.name.value),[node,operation]))})}},VariableDefinition:function(node){variableNameDefined[node.variable.name.value]=!0}}};var _error=require("../../error")},{"../../error":85}],149:[function(require,module,exports){"use strict";function unusedFragMessage(fragName){return'Fragment "'+fragName+'" is never used.'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.unusedFragMessage=unusedFragMessage,exports.NoUnusedFragments=function(context){var operationDefs=[],fragmentDefs=[];return{OperationDefinition:function(node){return operationDefs.push(node),!1},FragmentDefinition:function(node){return fragmentDefs.push(node),!1},Document:{leave:function(){var fragmentNameUsed=Object.create(null);operationDefs.forEach(function(operation){context.getRecursivelyReferencedFragments(operation).forEach(function(fragment){fragmentNameUsed[fragment.name.value]=!0})}),fragmentDefs.forEach(function(fragmentDef){var fragName=fragmentDef.name.value;!0!==fragmentNameUsed[fragName]&&context.reportError(new _error.GraphQLError(unusedFragMessage(fragName),[fragmentDef]))})}}}};var _error=require("../../error")},{"../../error":85}],150:[function(require,module,exports){"use strict";function unusedVariableMessage(varName,opName){return opName?'Variable "$'+varName+'" is never used in operation "'+opName+'".':'Variable "$'+varName+'" is never used.'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.unusedVariableMessage=unusedVariableMessage,exports.NoUnusedVariables=function(context){var variableDefs=[];return{OperationDefinition:{enter:function(){variableDefs=[]},leave:function(operation){var variableNameUsed=Object.create(null),usages=context.getRecursiveVariableUsages(operation),opName=operation.name?operation.name.value:null;usages.forEach(function(_ref){var node=_ref.node;variableNameUsed[node.name.value]=!0}),variableDefs.forEach(function(variableDef){var variableName=variableDef.variable.name.value;!0!==variableNameUsed[variableName]&&context.reportError(new _error.GraphQLError(unusedVariableMessage(variableName,opName),[variableDef]))})}},VariableDefinition:function(def){variableDefs.push(def)}}};var _error=require("../../error")},{"../../error":85}],151:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function fieldsConflictMessage(responseName,reason){return'Fields "'+responseName+'" conflict because '+reasonMessage(reason)+". Use different aliases on the fields to fetch both if this was intentional."}function reasonMessage(reason){return Array.isArray(reason)?reason.map(function(_ref){return'subfields "'+_ref[0]+'" conflict because '+reasonMessage(_ref[1])}).join(" and "):reason}function findConflictsWithinSelectionSet(context,cachedFieldsAndFragmentNames,comparedFragments,parentType,selectionSet){var conflicts=[],_getFieldsAndFragment=getFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,parentType,selectionSet),fieldMap=_getFieldsAndFragment[0],fragmentNames=_getFieldsAndFragment[1];collectConflictsWithin(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,fieldMap);for(var i=0;i<fragmentNames.length;i++){collectConflictsBetweenFieldsAndFragment(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,!1,fieldMap,fragmentNames[i]);for(var j=i+1;j<fragmentNames.length;j++)collectConflictsBetweenFragments(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,!1,fragmentNames[i],fragmentNames[j])}return conflicts}function collectConflictsBetweenFieldsAndFragment(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fieldMap,fragmentName){var fragment=context.getFragment(fragmentName);if(fragment){var _getReferencedFieldsA=getReferencedFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,fragment),fieldMap2=_getReferencedFieldsA[0],fragmentNames2=_getReferencedFieldsA[1];collectConflictsBetween(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fieldMap,fieldMap2);for(var i=0;i<fragmentNames2.length;i++)collectConflictsBetweenFieldsAndFragment(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fieldMap,fragmentNames2[i])}}function collectConflictsBetweenFragments(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fragmentName1,fragmentName2){var fragment1=context.getFragment(fragmentName1),fragment2=context.getFragment(fragmentName2);if(fragment1&&fragment2&&fragment1!==fragment2&&!comparedFragments.has(fragmentName1,fragmentName2,areMutuallyExclusive)){comparedFragments.add(fragmentName1,fragmentName2,areMutuallyExclusive);var _getReferencedFieldsA2=getReferencedFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,fragment1),fieldMap1=_getReferencedFieldsA2[0],fragmentNames1=_getReferencedFieldsA2[1],_getReferencedFieldsA3=getReferencedFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,fragment2),fieldMap2=_getReferencedFieldsA3[0],fragmentNames2=_getReferencedFieldsA3[1];collectConflictsBetween(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fieldMap1,fieldMap2);for(var j=0;j<fragmentNames2.length;j++)collectConflictsBetweenFragments(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fragmentName1,fragmentNames2[j]);for(var i=0;i<fragmentNames1.length;i++)collectConflictsBetweenFragments(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fragmentNames1[i],fragmentName2)}}function findConflictsBetweenSubSelectionSets(context,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,parentType1,selectionSet1,parentType2,selectionSet2){var conflicts=[],_getFieldsAndFragment2=getFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,parentType1,selectionSet1),fieldMap1=_getFieldsAndFragment2[0],fragmentNames1=_getFieldsAndFragment2[1],_getFieldsAndFragment3=getFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,parentType2,selectionSet2),fieldMap2=_getFieldsAndFragment3[0],fragmentNames2=_getFieldsAndFragment3[1];collectConflictsBetween(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fieldMap1,fieldMap2);for(var j=0;j<fragmentNames2.length;j++)collectConflictsBetweenFieldsAndFragment(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fieldMap1,fragmentNames2[j]);for(var i=0;i<fragmentNames1.length;i++)collectConflictsBetweenFieldsAndFragment(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fieldMap2,fragmentNames1[i]);for(var _i=0;_i<fragmentNames1.length;_i++)for(var _j=0;_j<fragmentNames2.length;_j++)collectConflictsBetweenFragments(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,fragmentNames1[_i],fragmentNames2[_j]);return conflicts}function collectConflictsWithin(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,fieldMap){Object.keys(fieldMap).forEach(function(responseName){var fields=fieldMap[responseName];if(fields.length>1)for(var i=0;i<fields.length;i++)for(var j=i+1;j<fields.length;j++){var conflict=findConflict(context,cachedFieldsAndFragmentNames,comparedFragments,!1,responseName,fields[i],fields[j]);conflict&&conflicts.push(conflict)}})}function collectConflictsBetween(context,conflicts,cachedFieldsAndFragmentNames,comparedFragments,parentFieldsAreMutuallyExclusive,fieldMap1,fieldMap2){Object.keys(fieldMap1).forEach(function(responseName){var fields2=fieldMap2[responseName];if(fields2)for(var fields1=fieldMap1[responseName],i=0;i<fields1.length;i++)for(var j=0;j<fields2.length;j++){var conflict=findConflict(context,cachedFieldsAndFragmentNames,comparedFragments,parentFieldsAreMutuallyExclusive,responseName,fields1[i],fields2[j]);conflict&&conflicts.push(conflict)}})}function findConflict(context,cachedFieldsAndFragmentNames,comparedFragments,parentFieldsAreMutuallyExclusive,responseName,field1,field2){var parentType1=field1[0],node1=field1[1],def1=field1[2],parentType2=field2[0],node2=field2[1],def2=field2[2],areMutuallyExclusive=parentFieldsAreMutuallyExclusive||parentType1!==parentType2&&parentType1 instanceof _definition.GraphQLObjectType&&parentType2 instanceof _definition.GraphQLObjectType,type1=def1&&def1.type,type2=def2&&def2.type;if(!areMutuallyExclusive){var name1=node1.name.value,name2=node2.name.value;if(name1!==name2)return[[responseName,name1+" and "+name2+" are different fields"],[node1],[node2]];if(!sameArguments(node1.arguments||[],node2.arguments||[]))return[[responseName,"they have differing arguments"],[node1],[node2]]}if(type1&&type2&&doTypesConflict(type1,type2))return[[responseName,"they return conflicting types "+String(type1)+" and "+String(type2)],[node1],[node2]];var selectionSet1=node1.selectionSet,selectionSet2=node2.selectionSet;return selectionSet1&&selectionSet2?subfieldConflicts(findConflictsBetweenSubSelectionSets(context,cachedFieldsAndFragmentNames,comparedFragments,areMutuallyExclusive,(0,_definition.getNamedType)(type1),selectionSet1,(0,_definition.getNamedType)(type2),selectionSet2),responseName,node1,node2):void 0}function sameArguments(arguments1,arguments2){return arguments1.length===arguments2.length&&arguments1.every(function(argument1){var argument2=(0,_find2.default)(arguments2,function(argument){return argument.name.value===argument1.name.value});return!!argument2&&sameValue(argument1.value,argument2.value)})}function sameValue(value1,value2){return!value1&&!value2||(0,_printer.print)(value1)===(0,_printer.print)(value2)}function doTypesConflict(type1,type2){return type1 instanceof _definition.GraphQLList?!(type2 instanceof _definition.GraphQLList)||doTypesConflict(type1.ofType,type2.ofType):type2 instanceof _definition.GraphQLList?!(type1 instanceof _definition.GraphQLList)||doTypesConflict(type1.ofType,type2.ofType):type1 instanceof _definition.GraphQLNonNull?!(type2 instanceof _definition.GraphQLNonNull)||doTypesConflict(type1.ofType,type2.ofType):type2 instanceof _definition.GraphQLNonNull?!(type1 instanceof _definition.GraphQLNonNull)||doTypesConflict(type1.ofType,type2.ofType):!(!(0,_definition.isLeafType)(type1)&&!(0,_definition.isLeafType)(type2))&&type1!==type2}function getFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,parentType,selectionSet){var cached=cachedFieldsAndFragmentNames.get(selectionSet);if(!cached){var nodeAndDefs=Object.create(null),fragmentNames=Object.create(null);_collectFieldsAndFragmentNames(context,parentType,selectionSet,nodeAndDefs,fragmentNames),cached=[nodeAndDefs,Object.keys(fragmentNames)],cachedFieldsAndFragmentNames.set(selectionSet,cached)}return cached}function getReferencedFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,fragment){var cached=cachedFieldsAndFragmentNames.get(fragment.selectionSet);return cached||getFieldsAndFragmentNames(context,cachedFieldsAndFragmentNames,(0,_typeFromAST.typeFromAST)(context.getSchema(),fragment.typeCondition),fragment.selectionSet)}function _collectFieldsAndFragmentNames(context,parentType,selectionSet,nodeAndDefs,fragmentNames){for(var i=0;i<selectionSet.selections.length;i++){var selection=selectionSet.selections[i];switch(selection.kind){case Kind.FIELD:var fieldName=selection.name.value,fieldDef=void 0;(parentType instanceof _definition.GraphQLObjectType||parentType instanceof _definition.GraphQLInterfaceType)&&(fieldDef=parentType.getFields()[fieldName]);var responseName=selection.alias?selection.alias.value:fieldName;nodeAndDefs[responseName]||(nodeAndDefs[responseName]=[]),nodeAndDefs[responseName].push([parentType,selection,fieldDef]);break;case Kind.FRAGMENT_SPREAD:fragmentNames[selection.name.value]=!0;break;case Kind.INLINE_FRAGMENT:var typeCondition=selection.typeCondition;_collectFieldsAndFragmentNames(context,typeCondition?(0,_typeFromAST.typeFromAST)(context.getSchema(),typeCondition):parentType,selection.selectionSet,nodeAndDefs,fragmentNames)}}}function subfieldConflicts(conflicts,responseName,node1,node2){if(conflicts.length>0)return[[responseName,conflicts.map(function(_ref3){return _ref3[0]})],conflicts.reduce(function(allFields,_ref4){var fields1=_ref4[1];return allFields.concat(fields1)},[node1]),conflicts.reduce(function(allFields,_ref5){var fields2=_ref5[2];return allFields.concat(fields2)},[node2])]}function _pairSetAdd(data,a,b,areMutuallyExclusive){var map=data[a];map||(map=Object.create(null),data[a]=map),map[b]=areMutuallyExclusive}Object.defineProperty(exports,"__esModule",{value:!0}),exports.fieldsConflictMessage=fieldsConflictMessage,exports.OverlappingFieldsCanBeMerged=function(context){var comparedFragments=new PairSet,cachedFieldsAndFragmentNames=new Map;return{SelectionSet:function(selectionSet){findConflictsWithinSelectionSet(context,cachedFieldsAndFragmentNames,comparedFragments,context.getParentType(),selectionSet).forEach(function(_ref2){var _ref2$=_ref2[0],responseName=_ref2$[0],reason=_ref2$[1],fields1=_ref2[1],fields2=_ref2[2];return context.reportError(new _error.GraphQLError(fieldsConflictMessage(responseName,reason),fields1.concat(fields2)))})}}};var _error=require("../../error"),_find2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../../jsutils/find")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../../language/kinds")),_printer=require("../../language/printer"),_definition=require("../../type/definition"),_typeFromAST=require("../../utilities/typeFromAST"),PairSet=function(){function PairSet(){_classCallCheck(this,PairSet),this._data=Object.create(null)}return PairSet.prototype.has=function(a,b,areMutuallyExclusive){var first=this._data[a],result=first&&first[b];return void 0!==result&&(!1!==areMutuallyExclusive||!1===result)},PairSet.prototype.add=function(a,b,areMutuallyExclusive){_pairSetAdd(this._data,a,b,areMutuallyExclusive),_pairSetAdd(this._data,b,a,areMutuallyExclusive)},PairSet}()},{"../../error":85,"../../jsutils/find":93,"../../language/kinds":102,"../../language/printer":106,"../../type/definition":112,"../../utilities/typeFromAST":135}],152:[function(require,module,exports){"use strict";function typeIncompatibleSpreadMessage(fragName,parentType,fragType){return'Fragment "'+fragName+'" cannot be spread here as objects of type "'+String(parentType)+'" can never be of type "'+String(fragType)+'".'}function typeIncompatibleAnonSpreadMessage(parentType,fragType){return'Fragment cannot be spread here as objects of type "'+String(parentType)+'" can never be of type "'+String(fragType)+'".'}function getFragmentType(context,name){var frag=context.getFragment(name);return frag&&(0,_typeFromAST.typeFromAST)(context.getSchema(),frag.typeCondition)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.typeIncompatibleSpreadMessage=typeIncompatibleSpreadMessage,exports.typeIncompatibleAnonSpreadMessage=typeIncompatibleAnonSpreadMessage,exports.PossibleFragmentSpreads=function(context){return{InlineFragment:function(node){var fragType=context.getType(),parentType=context.getParentType();fragType&&parentType&&!(0,_typeComparators.doTypesOverlap)(context.getSchema(),fragType,parentType)&&context.reportError(new _error.GraphQLError(typeIncompatibleAnonSpreadMessage(parentType,fragType),[node]))},FragmentSpread:function(node){var fragName=node.name.value,fragType=getFragmentType(context,fragName),parentType=context.getParentType();fragType&&parentType&&!(0,_typeComparators.doTypesOverlap)(context.getSchema(),fragType,parentType)&&context.reportError(new _error.GraphQLError(typeIncompatibleSpreadMessage(fragName,parentType,fragType),[node]))}}};var _error=require("../../error"),_typeComparators=require("../../utilities/typeComparators"),_typeFromAST=require("../../utilities/typeFromAST")},{"../../error":85,"../../utilities/typeComparators":134,"../../utilities/typeFromAST":135}],153:[function(require,module,exports){"use strict";function missingFieldArgMessage(fieldName,argName,type){return'Field "'+fieldName+'" argument "'+argName+'" of type "'+String(type)+'" is required but not provided.'}function missingDirectiveArgMessage(directiveName,argName,type){return'Directive "@'+directiveName+'" argument "'+argName+'" of type "'+String(type)+'" is required but not provided.'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.missingFieldArgMessage=missingFieldArgMessage,exports.missingDirectiveArgMessage=missingDirectiveArgMessage,exports.ProvidedNonNullArguments=function(context){return{Field:{leave:function(node){var fieldDef=context.getFieldDef();if(!fieldDef)return!1;var argNodes=node.arguments||[],argNodeMap=(0,_keyMap2.default)(argNodes,function(arg){return arg.name.value});fieldDef.args.forEach(function(argDef){!argNodeMap[argDef.name]&&argDef.type instanceof _definition.GraphQLNonNull&&context.reportError(new _error.GraphQLError(missingFieldArgMessage(node.name.value,argDef.name,argDef.type),[node]))})}},Directive:{leave:function(node){var directiveDef=context.getDirective();if(!directiveDef)return!1;var argNodes=node.arguments||[],argNodeMap=(0,_keyMap2.default)(argNodes,function(arg){return arg.name.value});directiveDef.args.forEach(function(argDef){!argNodeMap[argDef.name]&&argDef.type instanceof _definition.GraphQLNonNull&&context.reportError(new _error.GraphQLError(missingDirectiveArgMessage(node.name.value,argDef.name,argDef.type),[node]))})}}}};var _error=require("../../error"),_keyMap2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../../jsutils/keyMap")),_definition=require("../../type/definition")},{"../../error":85,"../../jsutils/keyMap":97,"../../type/definition":112}],154:[function(require,module,exports){"use strict";function noSubselectionAllowedMessage(fieldName,type){return'Field "'+fieldName+'" must not have a selection since type "'+String(type)+'" has no subfields.'}function requiredSubselectionMessage(fieldName,type){return'Field "'+fieldName+'" of type "'+String(type)+'" must have a selection of subfields. Did you mean "'+fieldName+' { ... }"?'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.noSubselectionAllowedMessage=noSubselectionAllowedMessage,exports.requiredSubselectionMessage=requiredSubselectionMessage,exports.ScalarLeafs=function(context){return{Field:function(node){var type=context.getType();type&&((0,_definition.isLeafType)((0,_definition.getNamedType)(type))?node.selectionSet&&context.reportError(new _error.GraphQLError(noSubselectionAllowedMessage(node.name.value,type),[node.selectionSet])):node.selectionSet||context.reportError(new _error.GraphQLError(requiredSubselectionMessage(node.name.value,type),[node])))}}};var _error=require("../../error"),_definition=require("../../type/definition")},{"../../error":85,"../../type/definition":112}],155:[function(require,module,exports){"use strict";function singleFieldOnlyMessage(name){return(name?'Subscription "'+name+'" ':"Anonymous Subscription ")+"must select only one top level field."}Object.defineProperty(exports,"__esModule",{value:!0}),exports.singleFieldOnlyMessage=singleFieldOnlyMessage,exports.SingleFieldSubscriptions=function(context){return{OperationDefinition:function(node){"subscription"===node.operation&&1!==node.selectionSet.selections.length&&context.reportError(new _error.GraphQLError(singleFieldOnlyMessage(node.name&&node.name.value),node.selectionSet.selections.slice(1)))}}};var _error=require("../../error")},{"../../error":85}],156:[function(require,module,exports){"use strict";function duplicateArgMessage(argName){return'There can be only one argument named "'+argName+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.duplicateArgMessage=duplicateArgMessage,exports.UniqueArgumentNames=function(context){var knownArgNames=Object.create(null);return{Field:function(){knownArgNames=Object.create(null)},Directive:function(){knownArgNames=Object.create(null)},Argument:function(node){var argName=node.name.value;return knownArgNames[argName]?context.reportError(new _error.GraphQLError(duplicateArgMessage(argName),[knownArgNames[argName],node.name])):knownArgNames[argName]=node.name,!1}}};var _error=require("../../error")},{"../../error":85}],157:[function(require,module,exports){"use strict";function duplicateDirectiveMessage(directiveName){return'The directive "'+directiveName+'" can only be used once at this location.'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.duplicateDirectiveMessage=duplicateDirectiveMessage,exports.UniqueDirectivesPerLocation=function(context){return{enter:function(node){if(node.directives){var knownDirectives=Object.create(null);node.directives.forEach(function(directive){var directiveName=directive.name.value;knownDirectives[directiveName]?context.reportError(new _error.GraphQLError(duplicateDirectiveMessage(directiveName),[knownDirectives[directiveName],directive])):knownDirectives[directiveName]=directive})}}}};var _error=require("../../error")},{"../../error":85}],158:[function(require,module,exports){"use strict";function duplicateFragmentNameMessage(fragName){return'There can be only one fragment named "'+fragName+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.duplicateFragmentNameMessage=duplicateFragmentNameMessage,exports.UniqueFragmentNames=function(context){var knownFragmentNames=Object.create(null);return{OperationDefinition:function(){return!1},FragmentDefinition:function(node){var fragmentName=node.name.value;return knownFragmentNames[fragmentName]?context.reportError(new _error.GraphQLError(duplicateFragmentNameMessage(fragmentName),[knownFragmentNames[fragmentName],node.name])):knownFragmentNames[fragmentName]=node.name,!1}}};var _error=require("../../error")},{"../../error":85}],159:[function(require,module,exports){"use strict";function duplicateInputFieldMessage(fieldName){return'There can be only one input field named "'+fieldName+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.duplicateInputFieldMessage=duplicateInputFieldMessage,exports.UniqueInputFieldNames=function(context){var knownNameStack=[],knownNames=Object.create(null);return{ObjectValue:{enter:function(){knownNameStack.push(knownNames),knownNames=Object.create(null)},leave:function(){knownNames=knownNameStack.pop()}},ObjectField:function(node){var fieldName=node.name.value;return knownNames[fieldName]?context.reportError(new _error.GraphQLError(duplicateInputFieldMessage(fieldName),[knownNames[fieldName],node.name])):knownNames[fieldName]=node.name,!1}}};var _error=require("../../error")},{"../../error":85}],160:[function(require,module,exports){"use strict";function duplicateOperationNameMessage(operationName){return'There can be only one operation named "'+operationName+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.duplicateOperationNameMessage=duplicateOperationNameMessage,exports.UniqueOperationNames=function(context){var knownOperationNames=Object.create(null);return{OperationDefinition:function(node){var operationName=node.name;return operationName&&(knownOperationNames[operationName.value]?context.reportError(new _error.GraphQLError(duplicateOperationNameMessage(operationName.value),[knownOperationNames[operationName.value],operationName])):knownOperationNames[operationName.value]=operationName),!1},FragmentDefinition:function(){return!1}}};var _error=require("../../error")},{"../../error":85}],161:[function(require,module,exports){"use strict";function duplicateVariableMessage(variableName){return'There can be only one variable named "'+variableName+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.duplicateVariableMessage=duplicateVariableMessage,exports.UniqueVariableNames=function(context){var knownVariableNames=Object.create(null);return{OperationDefinition:function(){knownVariableNames=Object.create(null)},VariableDefinition:function(node){var variableName=node.variable.name.value;knownVariableNames[variableName]?context.reportError(new _error.GraphQLError(duplicateVariableMessage(variableName),[knownVariableNames[variableName],node.variable.name])):knownVariableNames[variableName]=node.variable.name}}};var _error=require("../../error")},{"../../error":85}],162:[function(require,module,exports){"use strict";function nonInputTypeOnVarMessage(variableName,typeName){return'Variable "$'+variableName+'" cannot be non-input type "'+typeName+'".'}Object.defineProperty(exports,"__esModule",{value:!0}),exports.nonInputTypeOnVarMessage=nonInputTypeOnVarMessage,exports.VariablesAreInputTypes=function(context){return{VariableDefinition:function(node){var type=(0,_typeFromAST.typeFromAST)(context.getSchema(),node.type);if(type&&!(0,_definition.isInputType)(type)){var variableName=node.variable.name.value;context.reportError(new _error.GraphQLError(nonInputTypeOnVarMessage(variableName,(0,_printer.print)(node.type)),[node.type]))}}}};var _error=require("../../error"),_printer=require("../../language/printer"),_definition=require("../../type/definition"),_typeFromAST=require("../../utilities/typeFromAST")},{"../../error":85,"../../language/printer":106,"../../type/definition":112,"../../utilities/typeFromAST":135}],163:[function(require,module,exports){"use strict";function badVarPosMessage(varName,varType,expectedType){return'Variable "$'+varName+'" of type "'+String(varType)+'" used in position expecting type "'+String(expectedType)+'".'}function effectiveType(varType,varDef){return!varDef.defaultValue||varType instanceof _definition.GraphQLNonNull?varType:new _definition.GraphQLNonNull(varType)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.badVarPosMessage=badVarPosMessage,exports.VariablesInAllowedPosition=function(context){var varDefMap=Object.create(null);return{OperationDefinition:{enter:function(){varDefMap=Object.create(null)},leave:function(operation){context.getRecursiveVariableUsages(operation).forEach(function(_ref){var node=_ref.node,type=_ref.type,varName=node.name.value,varDef=varDefMap[varName];if(varDef&&type){var schema=context.getSchema(),varType=(0,_typeFromAST.typeFromAST)(schema,varDef.type);varType&&!(0,_typeComparators.isTypeSubTypeOf)(schema,effectiveType(varType,varDef),type)&&context.reportError(new _error.GraphQLError(badVarPosMessage(varName,varType,type),[varDef,node]))}})}},VariableDefinition:function(node){varDefMap[node.variable.name.value]=node}}};var _error=require("../../error"),_definition=require("../../type/definition"),_typeComparators=require("../../utilities/typeComparators"),_typeFromAST=require("../../utilities/typeFromAST")},{"../../error":85,"../../type/definition":112,"../../utilities/typeComparators":134,"../../utilities/typeFromAST":135}],164:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.specifiedRules=void 0;var _UniqueOperationNames=require("./rules/UniqueOperationNames"),_LoneAnonymousOperation=require("./rules/LoneAnonymousOperation"),_SingleFieldSubscriptions=require("./rules/SingleFieldSubscriptions"),_KnownTypeNames=require("./rules/KnownTypeNames"),_FragmentsOnCompositeTypes=require("./rules/FragmentsOnCompositeTypes"),_VariablesAreInputTypes=require("./rules/VariablesAreInputTypes"),_ScalarLeafs=require("./rules/ScalarLeafs"),_FieldsOnCorrectType=require("./rules/FieldsOnCorrectType"),_UniqueFragmentNames=require("./rules/UniqueFragmentNames"),_KnownFragmentNames=require("./rules/KnownFragmentNames"),_NoUnusedFragments=require("./rules/NoUnusedFragments"),_PossibleFragmentSpreads=require("./rules/PossibleFragmentSpreads"),_NoFragmentCycles=require("./rules/NoFragmentCycles"),_UniqueVariableNames=require("./rules/UniqueVariableNames"),_NoUndefinedVariables=require("./rules/NoUndefinedVariables"),_NoUnusedVariables=require("./rules/NoUnusedVariables"),_KnownDirectives=require("./rules/KnownDirectives"),_UniqueDirectivesPerLocation=require("./rules/UniqueDirectivesPerLocation"),_KnownArgumentNames=require("./rules/KnownArgumentNames"),_UniqueArgumentNames=require("./rules/UniqueArgumentNames"),_ArgumentsOfCorrectType=require("./rules/ArgumentsOfCorrectType"),_ProvidedNonNullArguments=require("./rules/ProvidedNonNullArguments"),_DefaultValuesOfCorrectType=require("./rules/DefaultValuesOfCorrectType"),_VariablesInAllowedPosition=require("./rules/VariablesInAllowedPosition"),_OverlappingFieldsCanBeMerged=require("./rules/OverlappingFieldsCanBeMerged"),_UniqueInputFieldNames=require("./rules/UniqueInputFieldNames");exports.specifiedRules=[_UniqueOperationNames.UniqueOperationNames,_LoneAnonymousOperation.LoneAnonymousOperation,_SingleFieldSubscriptions.SingleFieldSubscriptions,_KnownTypeNames.KnownTypeNames,_FragmentsOnCompositeTypes.FragmentsOnCompositeTypes,_VariablesAreInputTypes.VariablesAreInputTypes,_ScalarLeafs.ScalarLeafs,_FieldsOnCorrectType.FieldsOnCorrectType,_UniqueFragmentNames.UniqueFragmentNames,_KnownFragmentNames.KnownFragmentNames,_NoUnusedFragments.NoUnusedFragments,_PossibleFragmentSpreads.PossibleFragmentSpreads,_NoFragmentCycles.NoFragmentCycles,_UniqueVariableNames.UniqueVariableNames,_NoUndefinedVariables.NoUndefinedVariables,_NoUnusedVariables.NoUnusedVariables,_KnownDirectives.KnownDirectives,_UniqueDirectivesPerLocation.UniqueDirectivesPerLocation,_KnownArgumentNames.KnownArgumentNames,_UniqueArgumentNames.UniqueArgumentNames,_ArgumentsOfCorrectType.ArgumentsOfCorrectType,_ProvidedNonNullArguments.ProvidedNonNullArguments,_DefaultValuesOfCorrectType.DefaultValuesOfCorrectType,_VariablesInAllowedPosition.VariablesInAllowedPosition,_OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged,_UniqueInputFieldNames.UniqueInputFieldNames]},{"./rules/ArgumentsOfCorrectType":138,"./rules/DefaultValuesOfCorrectType":139,"./rules/FieldsOnCorrectType":140,"./rules/FragmentsOnCompositeTypes":141,"./rules/KnownArgumentNames":142,"./rules/KnownDirectives":143,"./rules/KnownFragmentNames":144,"./rules/KnownTypeNames":145,"./rules/LoneAnonymousOperation":146,"./rules/NoFragmentCycles":147,"./rules/NoUndefinedVariables":148,"./rules/NoUnusedFragments":149,"./rules/NoUnusedVariables":150,"./rules/OverlappingFieldsCanBeMerged":151,"./rules/PossibleFragmentSpreads":152,"./rules/ProvidedNonNullArguments":153,"./rules/ScalarLeafs":154,"./rules/SingleFieldSubscriptions":155,"./rules/UniqueArgumentNames":156,"./rules/UniqueDirectivesPerLocation":157,"./rules/UniqueFragmentNames":158,"./rules/UniqueInputFieldNames":159,"./rules/UniqueOperationNames":160,"./rules/UniqueVariableNames":161,"./rules/VariablesAreInputTypes":162,"./rules/VariablesInAllowedPosition":163}],165:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function visitUsingRules(schema,typeInfo,documentAST,rules){var context=new ValidationContext(schema,documentAST,typeInfo),visitors=rules.map(function(rule){return rule(context)});return(0,_visitor.visit)(documentAST,(0,_visitor.visitWithTypeInfo)(typeInfo,(0,_visitor.visitInParallel)(visitors))),context.getErrors()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.ValidationContext=void 0,exports.validate=function(schema,ast,rules,typeInfo){return(0,_invariant2.default)(schema,"Must provide schema"),(0,_invariant2.default)(ast,"Must provide document"),(0,_invariant2.default)(schema instanceof _schema.GraphQLSchema,"Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory."),visitUsingRules(schema,typeInfo||new _TypeInfo.TypeInfo(schema),ast,rules||_specifiedRules.specifiedRules)};var _invariant2=function(obj){return obj&&obj.__esModule?obj:{default:obj}}(require("../jsutils/invariant")),_visitor=(require("../error"),require("../language/visitor")),Kind=function(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}(require("../language/kinds")),_schema=require("../type/schema"),_TypeInfo=require("../utilities/TypeInfo"),_specifiedRules=require("./specifiedRules"),ValidationContext=exports.ValidationContext=function(){function ValidationContext(schema,ast,typeInfo){_classCallCheck(this,ValidationContext),this._schema=schema,this._ast=ast,this._typeInfo=typeInfo,this._errors=[],this._fragmentSpreads=new Map,this._recursivelyReferencedFragments=new Map,this._variableUsages=new Map,this._recursiveVariableUsages=new Map}return ValidationContext.prototype.reportError=function(error){this._errors.push(error)},ValidationContext.prototype.getErrors=function(){return this._errors},ValidationContext.prototype.getSchema=function(){return this._schema},ValidationContext.prototype.getDocument=function(){return this._ast},ValidationContext.prototype.getFragment=function(name){var fragments=this._fragments;return fragments||(this._fragments=fragments=this.getDocument().definitions.reduce(function(frags,statement){return statement.kind===Kind.FRAGMENT_DEFINITION&&(frags[statement.name.value]=statement),frags},Object.create(null))),fragments[name]},ValidationContext.prototype.getFragmentSpreads=function(node){var spreads=this._fragmentSpreads.get(node);if(!spreads){spreads=[];for(var setsToVisit=[node];0!==setsToVisit.length;)for(var set=setsToVisit.pop(),i=0;i<set.selections.length;i++){var selection=set.selections[i];selection.kind===Kind.FRAGMENT_SPREAD?spreads.push(selection):selection.selectionSet&&setsToVisit.push(selection.selectionSet)}this._fragmentSpreads.set(node,spreads)}return spreads},ValidationContext.prototype.getRecursivelyReferencedFragments=function(operation){var fragments=this._recursivelyReferencedFragments.get(operation);if(!fragments){fragments=[];for(var collectedNames=Object.create(null),nodesToVisit=[operation.selectionSet];0!==nodesToVisit.length;)for(var _node=nodesToVisit.pop(),spreads=this.getFragmentSpreads(_node),i=0;i<spreads.length;i++){var fragName=spreads[i].name.value;if(!0!==collectedNames[fragName]){collectedNames[fragName]=!0;var fragment=this.getFragment(fragName);fragment&&(fragments.push(fragment),nodesToVisit.push(fragment.selectionSet))}}this._recursivelyReferencedFragments.set(operation,fragments)}return fragments},ValidationContext.prototype.getVariableUsages=function(node){var usages=this._variableUsages.get(node);if(!usages){var newUsages=[],typeInfo=new _TypeInfo.TypeInfo(this._schema);(0,_visitor.visit)(node,(0,_visitor.visitWithTypeInfo)(typeInfo,{VariableDefinition:function(){return!1},Variable:function(variable){newUsages.push({node:variable,type:typeInfo.getInputType()})}})),usages=newUsages,this._variableUsages.set(node,usages)}return usages},ValidationContext.prototype.getRecursiveVariableUsages=function(operation){var usages=this._recursiveVariableUsages.get(operation);if(!usages){usages=this.getVariableUsages(operation);for(var fragments=this.getRecursivelyReferencedFragments(operation),i=0;i<fragments.length;i++)Array.prototype.push.apply(usages,this.getVariableUsages(fragments[i]));this._recursiveVariableUsages.set(operation,usages)}return usages},ValidationContext.prototype.getType=function(){return this._typeInfo.getType()},ValidationContext.prototype.getParentType=function(){return this._typeInfo.getParentType()},ValidationContext.prototype.getInputType=function(){return this._typeInfo.getInputType()},ValidationContext.prototype.getFieldDef=function(){return this._typeInfo.getFieldDef()},ValidationContext.prototype.getDirective=function(){return this._typeInfo.getDirective()},ValidationContext.prototype.getArgument=function(){return this._typeInfo.getArgument()},ValidationContext}()},{"../error":85,"../jsutils/invariant":94,"../language/kinds":102,"../language/visitor":108,"../type/schema":117,"../utilities/TypeInfo":118,"./specifiedRules":164}],166:[function(require,module,exports){function isIterable(obj){return!!getIteratorMethod(obj)}function isArrayLike(obj){var length=null!=obj&&obj.length;return"number"==typeof length&&length>=0&&length%1==0}function getIterator(iterable){var method=getIteratorMethod(iterable);if(method)return method.call(iterable)}function getIteratorMethod(iterable){if(null!=iterable){var method=SYMBOL_ITERATOR&&iterable[SYMBOL_ITERATOR]||iterable["@@iterator"];if("function"==typeof method)return method}}function createIterator(collection){if(null!=collection){var iterator=getIterator(collection);if(iterator)return iterator;if(isArrayLike(collection))return new ArrayLikeIterator(collection)}}function ArrayLikeIterator(obj){this._o=obj,this._i=0}function getAsyncIterator(asyncIterable){var method=getAsyncIteratorMethod(asyncIterable);if(method)return method.call(asyncIterable)}function getAsyncIteratorMethod(asyncIterable){if(null!=asyncIterable){var method=SYMBOL_ASYNC_ITERATOR&&asyncIterable[SYMBOL_ASYNC_ITERATOR]||asyncIterable["@@asyncIterator"];if("function"==typeof method)return method}}function createAsyncIterator(source){if(null!=source){var asyncIterator=getAsyncIterator(source);if(asyncIterator)return asyncIterator;var iterator=createIterator(source);if(iterator)return new AsyncFromSyncIterator(iterator)}}function AsyncFromSyncIterator(iterator){this._i=iterator}var SYMBOL_ITERATOR="function"==typeof Symbol&&Symbol.iterator,$$iterator=SYMBOL_ITERATOR||"@@iterator";exports.$$iterator=$$iterator,exports.isIterable=isIterable,exports.isArrayLike=isArrayLike,exports.isCollection=function(obj){return Object(obj)===obj&&(isArrayLike(obj)||isIterable(obj))},exports.getIterator=getIterator,exports.getIteratorMethod=getIteratorMethod,exports.createIterator=createIterator,ArrayLikeIterator.prototype[$$iterator]=function(){return this},ArrayLikeIterator.prototype.next=function(){return void 0===this._o||this._i>=this._o.length?(this._o=void 0,{value:void 0,done:!0}):{value:this._o[this._i++],done:!1}},exports.forEach=function(collection,callback,thisArg){if(null!=collection){if("function"==typeof collection.forEach)return collection.forEach(callback,thisArg);var i=0,iterator=getIterator(collection);if(iterator){for(var step;!(step=iterator.next()).done;)if(callback.call(thisArg,step.value,i++,collection),i>9999999)throw new TypeError("Near-infinite iteration.")}else if(isArrayLike(collection))for(;i<collection.length;i++)collection.hasOwnProperty(i)&&callback.call(thisArg,collection[i],i,collection)}};var SYMBOL_ASYNC_ITERATOR="function"==typeof Symbol&&Symbol.asyncIterator,$$asyncIterator=SYMBOL_ASYNC_ITERATOR||"@@asyncIterator";exports.$$asyncIterator=$$asyncIterator,exports.isAsyncIterable=function(obj){return!!getAsyncIteratorMethod(obj)},exports.getAsyncIterator=getAsyncIterator,exports.getAsyncIteratorMethod=getAsyncIteratorMethod,exports.createAsyncIterator=createAsyncIterator,AsyncFromSyncIterator.prototype[$$asyncIterator]=function(){return this},AsyncFromSyncIterator.prototype.next=function(){var step=this._i.next();return Promise.resolve(step.value).then(function(value){return{value:value,done:step.done}})},exports.forAwaitEach=function(source,callback,thisArg){function next(){return asyncIterator.next().then(function(step){if(!step.done)return Promise.resolve(callback.call(thisArg,step.value,i++,source)).then(next)})}var asyncIterator=createAsyncIterator(source);if(asyncIterator){var i=0;return next()}}},{}],167:[function(require,module,exports){(function(global){(function(){function Lexer(options){this.tokens=[],this.tokens.links={},this.options=options||marked.defaults,this.rules=block.normal,this.options.gfm&&(this.options.tables?this.rules=block.tables:this.rules=block.gfm)}function InlineLexer(links,options){if(this.options=options||marked.defaults,this.links=links,this.rules=inline.normal,this.renderer=this.options.renderer||new Renderer,this.renderer.options=this.options,!this.links)throw new Error("Tokens array requires a `links` property.");this.options.gfm?this.options.breaks?this.rules=inline.breaks:this.rules=inline.gfm:this.options.pedantic&&(this.rules=inline.pedantic)}function Renderer(options){this.options=options||{}}function Parser(options){this.tokens=[],this.token=null,this.options=options||marked.defaults,this.options.renderer=this.options.renderer||new Renderer,this.renderer=this.options.renderer,this.renderer.options=this.options}function escape(html,encode){return html.replace(encode?/&/g:/&(?!#?\w+;)/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function unescape(html){return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g,function(_,n){return"colon"===(n=n.toLowerCase())?":":"#"===n.charAt(0)?"x"===n.charAt(1)?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""})}function replace(regex,opt){return regex=regex.source,opt=opt||"",function self(name,val){return name?(val=val.source||val,val=val.replace(/(^|[^\[])\^/g,"$1"),regex=regex.replace(name,val),self):new RegExp(regex,opt)}}function noop(){}function merge(obj){for(var target,key,i=1;i<arguments.length;i++){target=arguments[i];for(key in target)Object.prototype.hasOwnProperty.call(target,key)&&(obj[key]=target[key])}return obj}function marked(src,opt,callback){if(callback||"function"==typeof opt){callback||(callback=opt,opt=null);var tokens,pending,highlight=(opt=merge({},marked.defaults,opt||{})).highlight,i=0;try{tokens=Lexer.lex(src,opt)}catch(e){return callback(e)}pending=tokens.length;var done=function(err){if(err)return opt.highlight=highlight,callback(err);var out;try{out=Parser.parse(tokens,opt)}catch(e){err=e}return opt.highlight=highlight,err?callback(err):callback(null,out)};if(!highlight||highlight.length<3)return done();if(delete opt.highlight,!pending)return done();for(;i<tokens.length;i++)!function(token){"code"!==token.type?--pending||done():highlight(token.text,token.lang,function(err,code){return err?done(err):null==code||code===token.text?--pending||done():(token.text=code,token.escaped=!0,void(--pending||done()))})}(tokens[i])}else try{return opt&&(opt=merge({},marked.defaults,opt)),Parser.parse(Lexer.lex(src,opt),opt)}catch(e){if(e.message+="\nPlease report this to https://github.com/chjj/marked.",(opt||marked.defaults).silent)return"<p>An error occured:</p><pre>"+escape(e.message+"",!0)+"</pre>";throw e}}var block={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:noop,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:noop,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:noop,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};block.bullet=/(?:[*+-]|\d+\.)/,block.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,block.item=replace(block.item,"gm")(/bull/g,block.bullet)(),block.list=replace(block.list)(/bull/g,block.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+block.def.source+")")(),block.blockquote=replace(block.blockquote)("def",block.def)(),block._tag="(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b",block.html=replace(block.html)("comment",/<!--[\s\S]*?-->/)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g,block._tag)(),block.paragraph=replace(block.paragraph)("hr",block.hr)("heading",block.heading)("lheading",block.lheading)("blockquote",block.blockquote)("tag","<"+block._tag)("def",block.def)(),block.normal=merge({},block),block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),block.gfm.paragraph=replace(block.paragraph)("(?!","(?!"+block.gfm.fences.source.replace("\\1","\\2")+"|"+block.list.source.replace("\\1","\\3")+"|")(),block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/}),Lexer.rules=block,Lexer.lex=function(src,options){return new Lexer(options).lex(src)},Lexer.prototype.lex=function(src){return src=src.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(src,!0)},Lexer.prototype.token=function(src,top,bq){for(var next,loose,cap,bull,b,item,space,i,l,src=src.replace(/^ +$/gm,"");src;)if((cap=this.rules.newline.exec(src))&&(src=src.substring(cap[0].length),cap[0].length>1&&this.tokens.push({type:"space"})),cap=this.rules.code.exec(src))src=src.substring(cap[0].length),cap=cap[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:this.options.pedantic?cap:cap.replace(/\n+$/,"")});else if(cap=this.rules.fences.exec(src))src=src.substring(cap[0].length),this.tokens.push({type:"code",lang:cap[2],text:cap[3]||""});else if(cap=this.rules.heading.exec(src))src=src.substring(cap[0].length),this.tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});else if(top&&(cap=this.rules.nptable.exec(src))){for(src=src.substring(cap[0].length),item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/\n$/,"").split("\n")},i=0;i<item.align.length;i++)/^ *-+: *$/.test(item.align[i])?item.align[i]="right":/^ *:-+: *$/.test(item.align[i])?item.align[i]="center":/^ *:-+ *$/.test(item.align[i])?item.align[i]="left":item.align[i]=null;for(i=0;i<item.cells.length;i++)item.cells[i]=item.cells[i].split(/ *\| */);this.tokens.push(item)}else if(cap=this.rules.lheading.exec(src))src=src.substring(cap[0].length),this.tokens.push({type:"heading",depth:"="===cap[2]?1:2,text:cap[1]});else if(cap=this.rules.hr.exec(src))src=src.substring(cap[0].length),this.tokens.push({type:"hr"});else if(cap=this.rules.blockquote.exec(src))src=src.substring(cap[0].length),this.tokens.push({type:"blockquote_start"}),cap=cap[0].replace(/^ *> ?/gm,""),this.token(cap,top,!0),this.tokens.push({type:"blockquote_end"});else if(cap=this.rules.list.exec(src)){for(src=src.substring(cap[0].length),bull=cap[2],this.tokens.push({type:"list_start",ordered:bull.length>1}),next=!1,l=(cap=cap[0].match(this.rules.item)).length,i=0;i<l;i++)space=(item=cap[i]).length,~(item=item.replace(/^ *([*+-]|\d+\.) +/,"")).indexOf("\n ")&&(space-=item.length,item=this.options.pedantic?item.replace(/^ {1,4}/gm,""):item.replace(new RegExp("^ {1,"+space+"}","gm"),"")),this.options.smartLists&&i!==l-1&&(bull===(b=block.bullet.exec(cap[i+1])[0])||bull.length>1&&b.length>1||(src=cap.slice(i+1).join("\n")+src,i=l-1)),loose=next||/\n\n(?!\s*$)/.test(item),i!==l-1&&(next="\n"===item.charAt(item.length-1),loose||(loose=next)),this.tokens.push({type:loose?"loose_item_start":"list_item_start"}),this.token(item,!1,bq),this.tokens.push({type:"list_item_end"});this.tokens.push({type:"list_end"})}else if(cap=this.rules.html.exec(src))src=src.substring(cap[0].length),this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&("pre"===cap[1]||"script"===cap[1]||"style"===cap[1]),text:cap[0]});else if(!bq&&top&&(cap=this.rules.def.exec(src)))src=src.substring(cap[0].length),this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};else if(top&&(cap=this.rules.table.exec(src))){for(src=src.substring(cap[0].length),item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,"").split("\n")},i=0;i<item.align.length;i++)/^ *-+: *$/.test(item.align[i])?item.align[i]="right":/^ *:-+: *$/.test(item.align[i])?item.align[i]="center":/^ *:-+ *$/.test(item.align[i])?item.align[i]="left":item.align[i]=null;for(i=0;i<item.cells.length;i++)item.cells[i]=item.cells[i].replace(/^ *\| *| *\| *$/g,"").split(/ *\| */);this.tokens.push(item)}else if(top&&(cap=this.rules.paragraph.exec(src)))src=src.substring(cap[0].length),this.tokens.push({type:"paragraph",text:"\n"===cap[1].charAt(cap[1].length-1)?cap[1].slice(0,-1):cap[1]});else if(cap=this.rules.text.exec(src))src=src.substring(cap[0].length),this.tokens.push({type:"text",text:cap[0]});else if(src)throw new Error("Infinite loop on byte: "+src.charCodeAt(0));return this.tokens};var inline={escape:/^\\([\\`*{}\[\]()#+\-.!_>])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:noop,tag:/^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/};inline._inside=/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/,inline._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/,inline.link=replace(inline.link)("inside",inline._inside)("href",inline._href)(),inline.reflink=replace(inline.reflink)("inside",inline._inside)(),inline.normal=merge({},inline),inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:replace(inline.text)("]|","~]|")("|","|https?://|")()}),inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()}),InlineLexer.rules=inline,InlineLexer.output=function(src,links,options){return new InlineLexer(links,options).output(src)},InlineLexer.prototype.output=function(src){for(var link,text,href,cap,out="";src;)if(cap=this.rules.escape.exec(src))src=src.substring(cap[0].length),out+=cap[1];else if(cap=this.rules.autolink.exec(src))src=src.substring(cap[0].length),"@"===cap[2]?(text=":"===cap[1].charAt(6)?this.mangle(cap[1].substring(7)):this.mangle(cap[1]),href=this.mangle("mailto:")+text):href=text=escape(cap[1]),out+=this.renderer.link(href,null,text);else if(this.inLink||!(cap=this.rules.url.exec(src))){if(cap=this.rules.tag.exec(src))!this.inLink&&/^<a /i.test(cap[0])?this.inLink=!0:this.inLink&&/^<\/a>/i.test(cap[0])&&(this.inLink=!1),src=src.substring(cap[0].length),out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0];else if(cap=this.rules.link.exec(src))src=src.substring(cap[0].length),this.inLink=!0,out+=this.outputLink(cap,{href:cap[2],title:cap[3]}),this.inLink=!1;else if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){if(src=src.substring(cap[0].length),link=(cap[2]||cap[1]).replace(/\s+/g," "),!(link=this.links[link.toLowerCase()])||!link.href){out+=cap[0].charAt(0),src=cap[0].substring(1)+src;continue}this.inLink=!0,out+=this.outputLink(cap,link),this.inLink=!1}else if(cap=this.rules.strong.exec(src))src=src.substring(cap[0].length),out+=this.renderer.strong(this.output(cap[2]||cap[1]));else if(cap=this.rules.em.exec(src))src=src.substring(cap[0].length),out+=this.renderer.em(this.output(cap[2]||cap[1]));else if(cap=this.rules.code.exec(src))src=src.substring(cap[0].length),out+=this.renderer.codespan(escape(cap[2],!0));else if(cap=this.rules.br.exec(src))src=src.substring(cap[0].length),out+=this.renderer.br();else if(cap=this.rules.del.exec(src))src=src.substring(cap[0].length),out+=this.renderer.del(this.output(cap[1]));else if(cap=this.rules.text.exec(src))src=src.substring(cap[0].length),out+=this.renderer.text(escape(this.smartypants(cap[0])));else if(src)throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}else src=src.substring(cap[0].length),href=text=escape(cap[1]),out+=this.renderer.link(href,null,text);return out},InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return"!"!==cap[0].charAt(0)?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]))},InlineLexer.prototype.smartypants=function(text){return this.options.smartypants?text.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):text},InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;for(var ch,out="",l=text.length,i=0;i<l;i++)ch=text.charCodeAt(i),Math.random()>.5&&(ch="x"+ch.toString(16)),out+="&#"+ch+";";return out},Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);null!=out&&out!==code&&(escaped=!0,code=out)}return lang?'<pre><code class="'+this.options.langPrefix+escape(lang,!0)+'">'+(escaped?code:escape(code,!0))+"\n</code></pre>\n":"<pre><code>"+(escaped?code:escape(code,!0))+"\n</code></pre>"},Renderer.prototype.blockquote=function(quote){return"<blockquote>\n"+quote+"</blockquote>\n"},Renderer.prototype.html=function(html){return html},Renderer.prototype.heading=function(text,level,raw){return"<h"+level+' id="'+this.options.headerPrefix+raw.toLowerCase().replace(/[^\w]+/g,"-")+'">'+text+"</h"+level+">\n"},Renderer.prototype.hr=function(){return this.options.xhtml?"<hr/>\n":"<hr>\n"},Renderer.prototype.list=function(body,ordered){var type=ordered?"ol":"ul";return"<"+type+">\n"+body+"</"+type+">\n"},Renderer.prototype.listitem=function(text){return"<li>"+text+"</li>\n"},Renderer.prototype.paragraph=function(text){return"<p>"+text+"</p>\n"},Renderer.prototype.table=function(header,body){return"<table>\n<thead>\n"+header+"</thead>\n<tbody>\n"+body+"</tbody>\n</table>\n"},Renderer.prototype.tablerow=function(content){return"<tr>\n"+content+"</tr>\n"},Renderer.prototype.tablecell=function(content,flags){var type=flags.header?"th":"td";return(flags.align?"<"+type+' style="text-align:'+flags.align+'">':"<"+type+">")+content+"</"+type+">\n"},Renderer.prototype.strong=function(text){return"<strong>"+text+"</strong>"},Renderer.prototype.em=function(text){return"<em>"+text+"</em>"},Renderer.prototype.codespan=function(text){return"<code>"+text+"</code>"},Renderer.prototype.br=function(){return this.options.xhtml?"<br/>":"<br>"},Renderer.prototype.del=function(text){return"<del>"+text+"</del>"},Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return""}if(0===prot.indexOf("javascript:")||0===prot.indexOf("vbscript:"))return""}var out='<a href="'+href+'"';return title&&(out+=' title="'+title+'"'),out+=">"+text+"</a>"},Renderer.prototype.image=function(href,title,text){var out='<img src="'+href+'" alt="'+text+'"';return title&&(out+=' title="'+title+'"'),out+=this.options.xhtml?"/>":">"},Renderer.prototype.text=function(text){return text},Parser.parse=function(src,options,renderer){return new Parser(options,renderer).parse(src)},Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer),this.tokens=src.reverse();for(var out="";this.next();)out+=this.tok();return out},Parser.prototype.next=function(){return this.token=this.tokens.pop()},Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},Parser.prototype.parseText=function(){for(var body=this.token.text;"text"===this.peek().type;)body+="\n"+this.next().text;return this.inline.output(body)},Parser.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var i,row,cell,j,header="",body="";for(cell="",i=0;i<this.token.header.length;i++)({header:!0,align:this.token.align[i]}),cell+=this.renderer.tablecell(this.inline.output(this.token.header[i]),{header:!0,align:this.token.align[i]});for(header+=this.renderer.tablerow(cell),i=0;i<this.token.cells.length;i++){for(row=this.token.cells[i],cell="",j=0;j<row.length;j++)cell+=this.renderer.tablecell(this.inline.output(row[j]),{header:!1,align:this.token.align[j]});body+=this.renderer.tablerow(cell)}return this.renderer.table(header,body);case"blockquote_start":for(body="";"blockquote_end"!==this.next().type;)body+=this.tok();return this.renderer.blockquote(body);case"list_start":for(var body="",ordered=this.token.ordered;"list_end"!==this.next().type;)body+=this.tok();return this.renderer.list(body,ordered);case"list_item_start":for(body="";"list_item_end"!==this.next().type;)body+="text"===this.token.type?this.parseText():this.tok();return this.renderer.listitem(body);case"loose_item_start":for(body="";"list_item_end"!==this.next().type;)body+=this.tok();return this.renderer.listitem(body);case"html":var html=this.token.pre||this.options.pedantic?this.token.text:this.inline.output(this.token.text);return this.renderer.html(html);case"paragraph":return this.renderer.paragraph(this.inline.output(this.token.text));case"text":return this.renderer.paragraph(this.parseText())}},noop.exec=noop,marked.options=marked.setOptions=function(opt){return merge(marked.defaults,opt),marked},marked.defaults={gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new Renderer,xhtml:!1},marked.Parser=Parser,marked.parser=Parser.parse,marked.Renderer=Renderer,marked.Lexer=Lexer,marked.lexer=Lexer.lex,marked.InlineLexer=InlineLexer,marked.inlineLexer=InlineLexer.output,marked.parse=marked,void 0!==module&&"object"==typeof exports?module.exports=marked:this.marked=marked}).call(function(){return this||("undefined"!=typeof window?window:global)}())}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],168:[function(require,module,exports){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&¤tQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}var cachedSetTimeout,cachedClearTimeout,process=module.exports={};!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],169:[function(require,module,exports){(function(process){"use strict";if("production"!==process.env.NODE_ENV)var invariant=require("fbjs/lib/invariant"),warning=require("fbjs/lib/warning"),ReactPropTypesSecret=require("./lib/ReactPropTypesSecret"),loggedTypeFailures={};module.exports=function(typeSpecs,values,location,componentName,getStack){if("production"!==process.env.NODE_ENV)for(var typeSpecName in typeSpecs)if(typeSpecs.hasOwnProperty(typeSpecName)){var error;try{invariant("function"==typeof typeSpecs[typeSpecName],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",componentName||"React class",location,typeSpecName),error=typeSpecs[typeSpecName](values,typeSpecName,componentName,location,null,ReactPropTypesSecret)}catch(ex){error=ex}if(warning(!error||error instanceof Error,"%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",componentName||"React class",location,typeSpecName,typeof error),error instanceof Error&&!(error.message in loggedTypeFailures)){loggedTypeFailures[error.message]=!0;var stack=getStack?getStack():"";warning(!1,"Failed %s type: %s%s",location,error.message,null!=stack?stack:"")}}}}).call(this,require("_process"))},{"./lib/ReactPropTypesSecret":173,_process:168,"fbjs/lib/invariant":65,"fbjs/lib/warning":66}],170:[function(require,module,exports){"use strict";var emptyFunction=require("fbjs/lib/emptyFunction"),invariant=require("fbjs/lib/invariant");module.exports=function(){function shim(){invariant(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function getShim(){return shim}shim.isRequired=shim;var ReactPropTypes={array:shim,bool:shim,func:shim,number:shim,object:shim,string:shim,symbol:shim,any:shim,arrayOf:getShim,element:shim,instanceOf:getShim,node:shim,objectOf:getShim,oneOf:getShim,oneOfType:getShim,shape:getShim};return ReactPropTypes.checkPropTypes=emptyFunction,ReactPropTypes.PropTypes=ReactPropTypes,ReactPropTypes}},{"fbjs/lib/emptyFunction":64,"fbjs/lib/invariant":65}],171:[function(require,module,exports){(function(process){"use strict";var emptyFunction=require("fbjs/lib/emptyFunction"),invariant=require("fbjs/lib/invariant"),warning=require("fbjs/lib/warning"),ReactPropTypesSecret=require("./lib/ReactPropTypesSecret"),checkPropTypes=require("./checkPropTypes");module.exports=function(isValidElement,throwOnDirectAccess){function getIteratorFn(maybeIterable){var iteratorFn=maybeIterable&&(ITERATOR_SYMBOL&&maybeIterable[ITERATOR_SYMBOL]||maybeIterable[FAUX_ITERATOR_SYMBOL]);if("function"==typeof iteratorFn)return iteratorFn}function is(x,y){return x===y?0!==x||1/x==1/y:x!==x&&y!==y}function PropTypeError(message){this.message=message,this.stack=""}function createChainableTypeChecker(validate){function checkType(isRequired,props,propName,componentName,location,propFullName,secret){if(componentName=componentName||ANONYMOUS,propFullName=propFullName||propName,secret!==ReactPropTypesSecret)if(throwOnDirectAccess)invariant(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");else if("production"!==process.env.NODE_ENV&&"undefined"!=typeof console){var cacheKey=componentName+":"+propName;!manualPropTypeCallCache[cacheKey]&&manualPropTypeWarningCount<3&&(warning(!1,"You are manually calling a React.PropTypes validation function for the `%s` prop on `%s`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.",propFullName,componentName),manualPropTypeCallCache[cacheKey]=!0,manualPropTypeWarningCount++)}return null==props[propName]?isRequired?new PropTypeError(null===props[propName]?"The "+location+" `"+propFullName+"` is marked as required in `"+componentName+"`, but its value is `null`.":"The "+location+" `"+propFullName+"` is marked as required in `"+componentName+"`, but its value is `undefined`."):null:validate(props,propName,componentName,location,propFullName)}if("production"!==process.env.NODE_ENV)var manualPropTypeCallCache={},manualPropTypeWarningCount=0;var chainedCheckType=checkType.bind(null,!1);return chainedCheckType.isRequired=checkType.bind(null,!0),chainedCheckType}function createPrimitiveTypeChecker(expectedType){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName,secret){var propValue=props[propName];return getPropType(propValue)!==expectedType?new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getPreciseType(propValue)+"` supplied to `"+componentName+"`, expected `"+expectedType+"`."):null})}function isNode(propValue){switch(typeof propValue){case"number":case"string":case"undefined":return!0;case"boolean":return!propValue;case"object":if(Array.isArray(propValue))return propValue.every(isNode);if(null===propValue||isValidElement(propValue))return!0;var iteratorFn=getIteratorFn(propValue);if(!iteratorFn)return!1;var step,iterator=iteratorFn.call(propValue);if(iteratorFn!==propValue.entries){for(;!(step=iterator.next()).done;)if(!isNode(step.value))return!1}else for(;!(step=iterator.next()).done;){var entry=step.value;if(entry&&!isNode(entry[1]))return!1}return!0;default:return!1}}function isSymbol(propType,propValue){return"symbol"===propType||("Symbol"===propValue["@@toStringTag"]||"function"==typeof Symbol&&propValue instanceof Symbol)}function getPropType(propValue){var propType=typeof propValue;return Array.isArray(propValue)?"array":propValue instanceof RegExp?"object":isSymbol(propType,propValue)?"symbol":propType}function getPreciseType(propValue){var propType=getPropType(propValue);if("object"===propType){if(propValue instanceof Date)return"date";if(propValue instanceof RegExp)return"regexp"}return propType}function getClassName(propValue){return propValue.constructor&&propValue.constructor.name?propValue.constructor.name:ANONYMOUS}var ITERATOR_SYMBOL="function"==typeof Symbol&&Symbol.iterator,FAUX_ITERATOR_SYMBOL="@@iterator",ANONYMOUS="<<anonymous>>",ReactPropTypes={array:createPrimitiveTypeChecker("array"),bool:createPrimitiveTypeChecker("boolean"),func:createPrimitiveTypeChecker("function"),number:createPrimitiveTypeChecker("number"),object:createPrimitiveTypeChecker("object"),string:createPrimitiveTypeChecker("string"),symbol:createPrimitiveTypeChecker("symbol"),any:createChainableTypeChecker(emptyFunction.thatReturnsNull),arrayOf:function(typeChecker){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){if("function"!=typeof typeChecker)return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside arrayOf.");var propValue=props[propName];if(!Array.isArray(propValue))return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getPropType(propValue)+"` supplied to `"+componentName+"`, expected an array.");for(var i=0;i<propValue.length;i++){var error=typeChecker(propValue,i,componentName,location,propFullName+"["+i+"]",ReactPropTypesSecret);if(error instanceof Error)return error}return null})},element:function(){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){var propValue=props[propName];return isValidElement(propValue)?null:new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getPropType(propValue)+"` supplied to `"+componentName+"`, expected a single ReactElement.")})}(),instanceOf:function(expectedClass){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){if(!(props[propName]instanceof expectedClass)){var expectedClassName=expectedClass.name||ANONYMOUS;return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+getClassName(props[propName])+"` supplied to `"+componentName+"`, expected instance of `"+expectedClassName+"`.")}return null})},node:function(){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){return isNode(props[propName])?null:new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to `"+componentName+"`, expected a ReactNode.")})}(),objectOf:function(typeChecker){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){if("function"!=typeof typeChecker)return new PropTypeError("Property `"+propFullName+"` of component `"+componentName+"` has invalid PropType notation inside objectOf.");var propValue=props[propName],propType=getPropType(propValue);if("object"!==propType)return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+propType+"` supplied to `"+componentName+"`, expected an object.");for(var key in propValue)if(propValue.hasOwnProperty(key)){var error=typeChecker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error instanceof Error)return error}return null})},oneOf:function(expectedValues){return Array.isArray(expectedValues)?createChainableTypeChecker(function(props,propName,componentName,location,propFullName){for(var propValue=props[propName],i=0;i<expectedValues.length;i++)if(is(propValue,expectedValues[i]))return null;return new PropTypeError("Invalid "+location+" `"+propFullName+"` of value `"+propValue+"` supplied to `"+componentName+"`, expected one of "+JSON.stringify(expectedValues)+".")}):("production"!==process.env.NODE_ENV&&warning(!1,"Invalid argument supplied to oneOf, expected an instance of array."),emptyFunction.thatReturnsNull)},oneOfType:function(arrayOfTypeCheckers){return Array.isArray(arrayOfTypeCheckers)?createChainableTypeChecker(function(props,propName,componentName,location,propFullName){for(var i=0;i<arrayOfTypeCheckers.length;i++)if(null==(0,arrayOfTypeCheckers[i])(props,propName,componentName,location,propFullName,ReactPropTypesSecret))return null;return new PropTypeError("Invalid "+location+" `"+propFullName+"` supplied to `"+componentName+"`.")}):("production"!==process.env.NODE_ENV&&warning(!1,"Invalid argument supplied to oneOfType, expected an instance of array."),emptyFunction.thatReturnsNull)},shape:function(shapeTypes){return createChainableTypeChecker(function(props,propName,componentName,location,propFullName){var propValue=props[propName],propType=getPropType(propValue);if("object"!==propType)return new PropTypeError("Invalid "+location+" `"+propFullName+"` of type `"+propType+"` supplied to `"+componentName+"`, expected `object`.");for(var key in shapeTypes){var checker=shapeTypes[key];if(checker){var error=checker(propValue,key,componentName,location,propFullName+"."+key,ReactPropTypesSecret);if(error)return error}}return null})}};return PropTypeError.prototype=Error.prototype,ReactPropTypes.checkPropTypes=checkPropTypes,ReactPropTypes.PropTypes=ReactPropTypes,ReactPropTypes}}).call(this,require("_process"))},{"./checkPropTypes":169,"./lib/ReactPropTypesSecret":173,_process:168,"fbjs/lib/emptyFunction":64,"fbjs/lib/invariant":65,"fbjs/lib/warning":66}],172:[function(require,module,exports){(function(process){if("production"!==process.env.NODE_ENV){var REACT_ELEMENT_TYPE="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;module.exports=require("./factoryWithTypeCheckers")(function(object){return"object"==typeof object&&null!==object&&object.$$typeof===REACT_ELEMENT_TYPE},!0)}else module.exports=require("./factoryWithThrowingShims")()}).call(this,require("_process"))},{"./factoryWithThrowingShims":170,"./factoryWithTypeCheckers":171,_process:168}],173:[function(require,module,exports){"use strict";module.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},{}],174:[function(require,module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],175:[function(require,module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],176:[function(require,module,exports){(function(process,global){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),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);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){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=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)&&(base=" [Function"+(value.name?": "+value.name:"")+"]"),isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),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")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i<l;++i)hasOwnProperty(value,String(i))?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if((desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]}).get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1)).indexOf("\n")>-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n")):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;(name=JSON.stringify(""+key)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;return output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i<arguments.length;i++)objects.push(inspect(arguments[i]));return objects.join(" ")}for(var i=1,args=arguments,len=args.length,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}}),x=args[i];i<len;x=args[++i])isNull(x)||!isObject(x)?str+=" "+x: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(!0===process.noDeprecation)return fn;var warned=!1;return function(){if(!warned){if(process.throwDeprecation)throw new Error(msg);process.traceDeprecation?console.trace(msg):console.error(msg),warned=!0}return fn.apply(this,arguments)}};var debugEnviron,debugs={};exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!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]},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"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=function(arg){return null==arg},exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=function(arg){return"symbol"==typeof arg},exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=function(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg},exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];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;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":175,_process:168,inherits:174}]},{},[21])(21)});
|
ajax/libs/react-cookie/0.1.2/react-cookie.js | Timbioz/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(require,module,exports){
var cookie = require('cookie');
var _cookies = cookie.parse((document && document.cookie) ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(name, val, opt) {
// Cookies only work in the browser
if (!document || !document.cookie) return;
_cookies[name] = val;
document.cookie = cookie.serialize(name, val, opt);
}
var reactCookie = {
load: load,
save: save
};
if (typeof module !== 'undefined') {
module.exports = reactCookie
}
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
}
},{"cookie":2}],2:[function(require,module,exports){
/// Serialize the a name value pair into a cookie string suitable for
/// http headers. An optional options object specified cookie parameters
///
/// serialize('foo', 'bar', { httpOnly: true })
/// => "foo=bar; httpOnly"
///
/// @param {String} name
/// @param {String} val
/// @param {Object} options
/// @return {String}
var serialize = function(name, val, opt){
opt = opt || {};
var enc = opt.encode || encode;
var pairs = [name + '=' + enc(val)];
if (null != opt.maxAge) {
var maxAge = opt.maxAge - 0;
if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
pairs.push('Max-Age=' + maxAge);
}
if (opt.domain) pairs.push('Domain=' + opt.domain);
if (opt.path) pairs.push('Path=' + opt.path);
if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString());
if (opt.httpOnly) pairs.push('HttpOnly');
if (opt.secure) pairs.push('Secure');
return pairs.join('; ');
};
/// Parse the given cookie header string into an object
/// The object has the various cookies as keys(names) => values
/// @param {String} str
/// @return {Object}
var parse = function(str, opt) {
opt = opt || {};
var obj = {}
var pairs = str.split(/; */);
var dec = opt.decode || decode;
pairs.forEach(function(pair) {
var eq_idx = pair.indexOf('=')
// skip things that don't look like key=value
if (eq_idx < 0) {
return;
}
var key = pair.substr(0, eq_idx).trim()
var val = pair.substr(++eq_idx, pair.length).trim();
// quoted values
if ('"' == val[0]) {
val = val.slice(1, -1);
}
// only assign once
if (undefined == obj[key]) {
try {
obj[key] = dec(val);
} catch (e) {
obj[key] = val;
}
}
});
return obj;
};
var encode = encodeURIComponent;
var decode = decodeURIComponent;
module.exports.serialize = serialize;
module.exports.parse = parse;
},{}]},{},[1]);
|
app/views/settings/elements/stock-cell.js | 7kfpun/FinanceReactNative | import React from 'react';
import PropTypes from 'prop-types';
import {
StyleSheet,
Text,
View,
} from 'react-native';
// 3rd party libraries
import Icon from 'react-native-vector-icons/MaterialIcons';
// Flux
import StockActions from '../../../actions/stock-action';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black',
flexDirection: 'row',
justifyContent: 'center',
marginHorizontal: 15,
height: 65,
borderBottomColor: '#CCCCCC',
borderBottomWidth: StyleSheet.hairlineWidth,
},
deleteIcon: {
flex: 1,
alignSelf: 'center',
},
deleteText: {
fontSize: 15,
color: '#FC3D39',
textAlign: 'left',
marginTop: 20,
marginBottom: 10,
marginRight: 10,
},
stock: {
flex: 8,
flexDirection: 'column',
},
symbol: {
flex: 1,
flexDirection: 'row',
},
symbolText: {
fontSize: 15,
color: 'white',
textAlign: 'left',
marginTop: 10,
marginBottom: 5,
marginRight: 10,
},
marketText: {
fontSize: 15,
color: '#A6A6A6',
textAlign: 'left',
marginTop: 10,
marginBottom: 5,
marginRight: 10,
},
name: {
flex: 1,
},
nameText: {
fontSize: 10,
color: 'white',
textAlign: 'left',
marginTop: 5,
marginBottom: 5,
marginRight: 10,
},
move: {
flex: 1,
alignSelf: 'center',
},
moveText: {
fontSize: 15,
color: 'white',
textAlign: 'left',
marginTop: 20,
marginBottom: 10,
marginRight: 10,
},
});
export default class StockCell extends React.Component {
onPressDelete(symbol) {
console.log('onPressDelete', symbol);
StockActions.deleteStock(symbol);
}
render() {
return (
<View style={styles.container}>
<Icon
style={styles.deleteIcon}
name="remove-circle"
color="red"
size={22}
onPress={() => this.onPressDelete(this.props.stock.symbol)}
/>
<View style={styles.stock}>
<View style={styles.symbol}>
<Text style={styles.symbolText}>
{this.props.stock.symbol}
</Text>
<Text style={styles.marketText}>
{this.props.watchlistResult && this.props.watchlistResult[this.props.stock.symbol] && this.props.watchlistResult[this.props.stock.symbol].StockExchange}
</Text>
</View>
<View style={styles.name}>
<Text style={styles.nameText}>
{this.props.watchlistResult && this.props.watchlistResult[this.props.stock.symbol] && this.props.watchlistResult[this.props.stock.symbol].Name}
</Text>
</View>
</View>
<Icon style={styles.move} name="menu" color="white" size={22} />
</View>
);
}
}
StockCell.propTypes = {
watchlistResult: PropTypes.shape({}),
stock: PropTypes.shape({
symbol: PropTypes.string,
}),
};
StockCell.defaultProps = {
watchlistResult: [],
stock: {},
};
|
ajax/libs/react/15.3.0/react-dom-server.js | jonobr1/cdnjs | /**
* ReactDOMServer v15.3.0
*
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// Based off https://github.com/ForbesLindesay/umd/blob/master/template.js
;(function(f) {
// CommonJS
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f(require('react'));
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(['react'], f);
// <script>
} else {
var g;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
// works providing we're not in "use strict";
// needed for Java 8 Nashorn
// see https://github.com/facebook/react/issues/3037
g = this;
}
g.ReactDOMServer = f(g.React);
}
})(function(React) {
return React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
});
|
goazuredocker/wwwroot/lib/jquery/js/jquery.js | buchizo/goazure | /*!
* jQuery JavaScript Library v1.10.2
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-07-03T13:48Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.2",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// 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 default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, 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({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.10.2
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-07-03
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent.attachEvent && parent !== parent.top ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return (val = elem.getAttributeNode( name )) && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
});
}
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.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
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// 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)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// 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).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior.
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// 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 = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and 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
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
})( window );
|
packages/reactor-kitchensink/src/NavView.js | markbrocato/extjs-reactor | import React from 'react';
import { Container } from '@extjs/ext-react';
export default function NavView({ node }) {
function onClick(e, path) {
Ext.get(e.target).ripple(e, {});
requestAnimationFrame(() => location.hash = path, 50)
}
return (
<Container layout="center" padding="20" scrollable className="app-navview">
<div style={{textAlign: 'center'}}>
{ node && node.childNodes.map((child, i) => (
<div key={i} className="app-thumbnail">
<div className="app-thumbnail-icon-wrap" onClick={e => onClick(e, child.id)}>
<div className={`app-thumbnail-icon ${child.data.navIcon}`}/>
</div>
<div className="app-thumbnail-text">{child.data.name}</div>
{child.data.premium && <div className="x-fa fa-star app-premium-indicator"/>}
</div>
)) }
</div>
</Container>
)
} |
src/pages/resume/components/preface.js | dan9186/danielhess.me | import React from 'react'
import styled from 'styled-components'
import { Section } from '../../../components/grid'
export const Preface = ({ preface }) => (
<Section>
<Content>{preface}</Content>
</Section>
)
const Content = styled.div`
display: flex;
flex-flow: row wrap;
margin-top: ${({ theme }) => theme.spacing(2)};
margin-bottom: ${({ theme }) => theme.spacing(0)};
padding-left: ${({ theme }) => theme.spacing(2)};
`
|
packages/wix-style-react/src/BrowserPreviewWidget/docs/index.story.js | wix/wix-style-react | import React from 'react';
import {
header,
tabs,
tab,
description,
importExample,
title,
columns,
divider,
example,
playground,
api,
testkit,
} from 'wix-storybook-utils/Sections';
import { storySettings } from '../test/storySettings';
import BrowserPreviewWidget from '..';
import { skins, browserBarSizes } from '../constants';
import { Box, Text } from 'wix-style-react';
const childNode = (
<Box padding="20px" backgroundColor="Y30">
<Text>Content goes here</Text>
</Box>
);
const childNodeString = `<Box padding="20px" backgroundColor="Y30">
<Text>Content goes here</Text>
</Box>`;
export default {
category: storySettings.category,
storyName: 'BrowserPreviewWidget',
component: BrowserPreviewWidget,
componentPath: '..',
componentProps: {
skin: skins.neutral,
backgroundColor: '',
browserBarSize: browserBarSizes.size12,
height: '100%',
width: '100%',
children: childNode,
},
sections: [
header({
component: (
<BrowserPreviewWidget
browserBarSize="size9"
height="130px"
width="230px"
>
{childNode}
</BrowserPreviewWidget>
),
}),
tabs([
tab({
title: 'Description',
sections: [
description({
title: 'Description',
text:
'Browser preview widget. Displays custom content within a browser display.',
}),
importExample(
"import { BrowserPreviewWidget } from 'wix-style-react';",
),
divider(),
title('Examples'),
example({
title: 'Skin',
text:
'BrowserPreviewWidget supports `neutral` (default), `gradient` and `custom` skins. To use custom skin, set it to `custom` and use the `backgroundColor` prop with the desired color',
source: `<Layout>
<Cell>
<BrowserPreviewWidget browserBarSize="${browserBarSizes.size9}">${childNodeString}</BrowserPreviewWidget>
</Cell>
<Cell>
<BrowserPreviewWidget browserBarSize="${browserBarSizes.size9}" skin='gradient'>${childNodeString}</BrowserPreviewWidget>
</Cell>
<Cell>
<BrowserPreviewWidget browserBarSize="${browserBarSizes.size9}" skin='custom' backgroundColor='B10'>${childNodeString}</BrowserPreviewWidget>
</Cell>
</Layout>`,
}),
example({
title: 'Browser Bar Size',
text: `BrowserPreviewWidget supports 4 browser bar sizes: \`${browserBarSizes.size9}\`, \`${browserBarSizes.size12}\` (default), \`${browserBarSizes.size18}\` and \`${browserBarSizes.size24}\`.
| Browser Bar Height | Width |
| --- | --- |
| ${browserBarSizes.size9} | 0 < w < 312 |
| ${browserBarSizes.size12} | 312 ≤ w < 444 |
| ${browserBarSizes.size18} | 444 ≤ w < 660 |
| ${browserBarSizes.size24} | 660 ≤ w |
`,
source: `<Layout>
<Cell>
<BrowserPreviewWidget browserBarSize="${browserBarSizes.size9}">
<Box width="250px" height="100px" backgroundColor="Y30"/>
</BrowserPreviewWidget>
</Cell>
<Cell>
<BrowserPreviewWidget>
<Box width="350px" height="100px" backgroundColor="Y30"/>
</BrowserPreviewWidget>
</Cell>
<Cell>
<BrowserPreviewWidget browserBarSize="${browserBarSizes.size18}">
<Box width="450px" height="100px" backgroundColor="Y30"/>
</BrowserPreviewWidget>
</Cell>
<Cell>
<BrowserPreviewWidget browserBarSize="${browserBarSizes.size24}">
<Box width="700px" height="100px" backgroundColor="Y30"/>
</BrowserPreviewWidget>
</Cell>
</Layout>`,
}),
],
}),
...[
{ title: 'API', sections: [api()] },
{ title: 'Testkit', sections: [testkit()] },
{ title: 'Playground', sections: [playground()] },
].map(tab),
]),
],
};
|
ajax/libs/analytics.js/1.5.0/analytics.min.js | hongkheng/cdnjs | (function(){function require(path,parent,orig){var resolved=require.resolve(path);if(null==resolved){orig=orig||path;parent=parent||"root";var err=new Error('Failed to require "'+orig+'" from "'+parent+'"');err.path=orig;err.parent=parent;err.require=true;throw err}var module=require.modules[resolved];if(!module._resolving&&!module.exports){var mod={};mod.exports={};mod.client=mod.component=true;module._resolving=true;module.call(this,mod.exports,require.relative(resolved),mod);delete module._resolving;module.exports=mod.exports}return module.exports}require.modules={};require.aliases={};require.resolve=function(path){if(path.charAt(0)==="/")path=path.slice(1);var paths=[path,path+".js",path+".json",path+"/index.js",path+"/index.json"];for(var i=0;i<paths.length;i++){var path=paths[i];if(require.modules.hasOwnProperty(path))return path;if(require.aliases.hasOwnProperty(path))return require.aliases[path]}};require.normalize=function(curr,path){var segs=[];if("."!=path.charAt(0))return path;curr=curr.split("/");path=path.split("/");for(var i=0;i<path.length;++i){if(".."==path[i]){curr.pop()}else if("."!=path[i]&&""!=path[i]){segs.push(path[i])}}return curr.concat(segs).join("/")};require.register=function(path,definition){require.modules[path]=definition};require.alias=function(from,to){if(!require.modules.hasOwnProperty(from)){throw new Error('Failed to alias "'+from+'", it does not exist')}require.aliases[to]=from};require.relative=function(parent){var p=require.normalize(parent,"..");function lastIndexOf(arr,obj){var i=arr.length;while(i--){if(arr[i]===obj)return i}return-1}function localRequire(path){var resolved=localRequire.resolve(path);return require(resolved,parent,path)}localRequire.resolve=function(path){var c=path.charAt(0);if("/"==c)return path.slice(1);if("."==c)return require.normalize(p,path);var segs=parent.split("/");var i=lastIndexOf(segs,"deps")+1;if(!i)i=0;path=segs.slice(0,i+1).join("/")+"/deps/"+path;return path};localRequire.exists=function(path){return require.modules.hasOwnProperty(localRequire.resolve(path))};return localRequire};require.register("avetisk-defaults/index.js",function(exports,require,module){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults});require.register("component-type/index.js",function(exports,require,module){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}if(val===null)return"null";if(val===undefined)return"undefined";if(val!==val)return"nan";if(val&&val.nodeType===1)return"element";val=val.valueOf?val.valueOf():Object.prototype.valueOf.apply(val);return typeof val}});require.register("component-clone/index.js",function(exports,require,module){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}});require.register("component-cookie/index.js",function(exports,require,module){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}});require.register("component-each/index.js",function(exports,require,module){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}});require.register("component-indexof/index.js",function(exports,require,module){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}});require.register("component-emitter/index.js",function(exports,require,module){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}});require.register("component-event/index.js",function(exports,require,module){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}});require.register("component-inherit/index.js",function(exports,require,module){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}});require.register("component-object/index.js",function(exports,require,module){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}});require.register("component-trim/index.js",function(exports,require,module){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}});require.register("component-querystring/index.js",function(exports,require,module){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}});require.register("component-url/index.js",function(exports,require,module){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}});require.register("component-bind/index.js",function(exports,require,module){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}});require.register("segmentio-bind-all/index.js",function(exports,require,module){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}});require.register("ianstormtaylor-bind/index.js",function(exports,require,module){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}});require.register("timoxley-next-tick/index.js",function(exports,require,module){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}});require.register("ianstormtaylor-callback/index.js",function(exports,require,module){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback});require.register("ianstormtaylor-is-empty/index.js",function(exports,require,module){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}});require.register("ianstormtaylor-is/index.js",function(exports,require,module){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}});require.register("segmentio-after/index.js",function(exports,require,module){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}});require.register("component-domify/index.js",function(exports,require,module){module.exports=parse;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=document.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}});require.register("component-once/index.js",function(exports,require,module){var n=0;var global=function(){return this}();module.exports=function(fn){var id=n++;function once(){if(this==global){if(once.called)return;once.called=true;return fn.apply(this,arguments)}var key="__called_"+id+"__";if(this[key])return;this[key]=true;return fn.apply(this,arguments)}return once}});require.register("segmentio-alias/index.js",function(exports,require,module){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}});require.register("ianstormtaylor-to-no-case/index.js",function(exports,require,module){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}});require.register("segmentio-analytics.js-integration/lib/index.js",function(exports,require,module){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this._wrapInitialize();this._wrapLoad();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}});require.register("segmentio-analytics.js-integration/lib/protos.js",function(exports,require,module){var normalize=require("to-no-case");var after=require("after");var callback=require("callback");var Emitter=require("emitter");var tick=require("next-tick");var events=require("./events");var type=require("type");Emitter(exports);exports.initialize=function(){this.load()};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");var self=this;if(this._readyOnInitialize){tick(function(){self.emit("ready")})}return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapLoad=function(){var load=this.load;this.load=function(callback){var self=this;this.debug("loading");if(this.loaded()){this.debug("already loaded");tick(function(){if(self._readyOnLoad)self.emit("ready");callback&&callback()});return}return load.call(this,function(err,e){self.debug("loaded");self.emit("load");if(self._readyOnLoad)self.emit("ready");callback&&callback(err,e)})}};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}}});require.register("segmentio-analytics.js-integration/lib/events.js",function(exports,require,module){module.exports={removedProduct:/removed[ _]?product/i,viewedProduct:/viewed[ _]?product/i,addedProduct:/added[ _]?product/i,completedOrder:/completed[ _]?order/i}});require.register("segmentio-analytics.js-integration/lib/statics.js",function(exports,require,module){var after=require("after");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this}});require.register("segmentio-convert-dates/index.js",function(exports,require,module){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}});require.register("segmentio-global-queue/index.js",function(exports,require,module){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}});require.register("segmentio-load-date/index.js",function(exports,require,module){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time});require.register("segmentio-load-script/index.js",function(exports,require,module){var type=require("type");module.exports=function loadScript(options,callback){if(!options)throw new Error("Cant load nothing...");if(type(options)==="string")options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript);if(callback&&type(callback)==="function"){if(script.addEventListener){script.addEventListener("load",function(event){callback(null,event)},false);script.addEventListener("error",function(event){callback(new Error("Failed to load the script."),event)},false)}else if(script.attachEvent){script.attachEvent("onreadystatechange",function(event){if(/complete|loaded/.test(script.readyState)){callback(null,event)}})}}return script}});require.register("segmentio-script-onload/index.js",function(exports,require,module){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)})}});require.register("segmentio-on-body/index.js",function(exports,require,module){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}});require.register("segmentio-on-error/index.js",function(exports,require,module){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}});require.register("segmentio-to-iso-string/index.js",function(exports,require,module){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}});require.register("segmentio-to-unix-timestamp/index.js",function(exports,require,module){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}});require.register("segmentio-use-https/index.js",function(exports,require,module){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}});require.register("segmentio-when/index.js",function(exports,require,module){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}});require.register("yields-slug/index.js",function(exports,require,module){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}});require.register("visionmedia-batch/index.js",function(exports,require,module){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}});require.register("segmentio-substitute/index.js",function(exports,require,module){module.exports=substitute;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){return null!=obj[prop]?obj[prop]:_})}});require.register("segmentio-load-pixel/index.js",function(exports,require,module){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}});require.register("segmentio-replace-document-write/index.js",function(exports,require,module){var domify=require("domify");module.exports=function(match,parent,fn){var write=document.write;document.write=append;if(typeof parent==="function")fn=parent,parent=null;if(!parent)parent=document.body;function append(str){var el=domify(str);var src=el.src||"";if(el.src.indexOf(match)===-1)return write(str);if("SCRIPT"==el.tagName)el=recreate(el);parent.appendChild(el);document.write=write;fn&&fn()}};function recreate(script){var ret=document.createElement("script");ret.src=script.src;ret.async=script.async;ret.defer=script.defer;return ret}});require.register("ianstormtaylor-to-camel-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-capital-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}});require.register("ianstormtaylor-to-constant-case/index.js",function(exports,require,module){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}});require.register("ianstormtaylor-to-dot-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}});require.register("ianstormtaylor-to-pascal-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-sentence-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-to-slug-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}});require.register("ianstormtaylor-to-snake-case/index.js",function(exports,require,module){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}});require.register("ianstormtaylor-to-space-case/index.js",function(exports,require,module){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}});require.register("component-escape-regexp/index.js",function(exports,require,module){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}});require.register("ianstormtaylor-map/index.js",function(exports,require,module){var each=require("each");
module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}});require.register("ianstormtaylor-title-case-minors/index.js",function(exports,require,module){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]});require.register("ianstormtaylor-to-title-case/index.js",function(exports,require,module){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}});require.register("ianstormtaylor-case/lib/index.js",function(exports,require,module){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}});require.register("ianstormtaylor-case/lib/cases.js",function(exports,require,module){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none});require.register("segmentio-obj-case/index.js",function(exports,require,module){var Case=require("case");var cases=[Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}});require.register("segmentio-analytics.js-integrations/index.js",function(exports,require,module){var integrations=require("./lib/slugs");var each=require("each");each(integrations,function(slug){var plugin=require("./lib/"+slug);var name=plugin.Integration.prototype.name;exports[name]=plugin})});require.register("segmentio-analytics.js-integrations/lib/adroll.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");var user;var has=Object.prototype.hasOwnProperty;module.exports=exports=function(analytics){analytics.addIntegration(AdRoll);user=analytics.user()};var AdRoll=exports.Integration=integration("AdRoll").assumesPageview().readyOnLoad().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("events",{}).option("advId","").option("pixId","");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;if(user.id())window.adroll_custom_data={USER_ID:user.id()};window.__adroll_loaded=true;this.load()};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.load=function(callback){load({http:"http://a.adroll.com/j/roundtrip.js",https:"https://s.adroll.com/j/roundtrip.js"},callback)};AdRoll.prototype.track=function(track){var events=this.options.events;var total=track.revenue();var event=track.event();if(has.call(events,event))event=events[event];window.__adroll.record_user({adroll_conversion_value_in_dollars:total||0,order_id:track.orderId()||0,adroll_segments:event})}});require.register("segmentio-analytics.js-integrations/lib/adwords.js",function(exports,require,module){var onbody=require("on-body");var integration=require("integration");var load=require("load-script");var domify=require("domify");module.exports=exports=function(analytics){analytics.addIntegration(AdWords)};var has=Object.prototype.hasOwnProperty;var AdWords=exports.Integration=integration("AdWords").readyOnLoad().option("conversionId","").option("events",{});AdWords.prototype.load=function(fn){onbody(fn)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.options.events;var event=track.event();if(!has.call(events,event))return;return this.conversion({value:track.revenue()||0,label:events[event],conversionId:id})};AdWords.prototype.conversion=function(obj,fn){if(this.reporting)return this.wait(obj);this.reporting=true;this.debug("sending %o",obj);var self=this;var write=document.write;document.write=append;window.google_conversion_id=obj.conversionId;window.google_conversion_language="en";window.google_conversion_format="3";window.google_conversion_color="ffffff";window.google_conversion_label=obj.label;window.google_conversion_value=obj.value;window.google_remarketing_only=false;load("//www.googleadservices.com/pagead/conversion.js",fn);function append(str){var el=domify(str);if(!el.src)return write(str);if(!/googleadservices/.test(el.src))return write(str);self.debug("append %o",el);document.body.appendChild(el);document.write=write;self.reporting=null}};AdWords.prototype.wait=function(obj){var self=this;var id=setTimeout(function(){clearTimeout(id);self.conversion(obj)},50)}});require.register("segmentio-analytics.js-integrations/lib/alexa.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Alexa)};var Alexa=exports.Integration=integration("Alexa").assumesPageview().readyOnLoad().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true);Alexa.prototype.initialize=function(page){window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load()};Alexa.prototype.loaded=function(){return!!window.atrk};Alexa.prototype.load=function(callback){load("//d31qbv1cthcecs.cloudfront.net/atrk.js",function(err){if(err)return callback(err);window.atrk();callback()})}});require.register("segmentio-analytics.js-integrations/lib/amplitude.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Amplitude)};var Amplitude=exports.Integration=integration("Amplitude").assumesPageview().readyOnInitialize().global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true);Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load()};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.load=function(callback){load("https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js",callback)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)}});require.register("segmentio-analytics.js-integrations/lib/awesm.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Awesm);user=analytics.user()};var Awesm=exports.Integration=integration("awe.sm").assumesPageview().readyOnLoad().global("AWESM").option("apiKey","").option("events",{});Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load()};Awesm.prototype.loaded=function(){return!!window.AWESM._exists};Awesm.prototype.load=function(callback){var key=this.options.apiKey;load("//widgets.awe.sm/v3/widgets.js?key="+key+"&async=true",callback)};Awesm.prototype.track=function(track){var event=track.event();var goal=this.options.events[event];if(!goal)return;window.AWESM.convert(goal,track.cents(),null,user.id())}});require.register("segmentio-analytics.js-integrations/lib/awesomatic.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");var noop=function(){};var onBody=require("on-body");var user;module.exports=exports=function(analytics){analytics.addIntegration(Awesomatic);user=analytics.user()};var Awesomatic=exports.Integration=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","");Awesomatic.prototype.initialize=function(page){var self=this;var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.emit("ready")})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)};Awesomatic.prototype.load=function(callback){var url="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js";load(url,callback)}});require.register("segmentio-analytics.js-integrations/lib/bing-ads.js",function(exports,require,module){var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(Bing)};var has=Object.prototype.hasOwnProperty;var Bing=exports.Integration=integration("Bing Ads").readyOnInitialize().option("siteId","").option("domainId","").option("goals",{});Bing.prototype.track=function(track){var goals=this.options.goals;var traits=track.traits();var event=track.event();if(!has.call(goals,event))return;var goal=goals[event];return exports.load(goal,track.revenue(),this.options)};exports.load=function(goal,revenue,options){var iframe=document.createElement("iframe");iframe.src="//flex.msn.com/mstag/tag/"+options.siteId+"/analytics.html"+"?domainId="+options.domainId+"&revenue="+revenue||0+"&actionid="+goal;+"&dedup=1"+"&type=1";iframe.width=1;iframe.height=1;return iframe}});require.register("segmentio-analytics.js-integrations/lib/bronto.js",function(exports,require,module){var integration=require("integration");var Track=require("facade").Track;var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(Bronto)};var Bronto=exports.Integration=integration("Bronto").readyOnLoad().global("__bta").option("siteId","").option("host","");Bronto.prototype.initialize=function(page){this.load()};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.load=function(fn){var self=this;load("//p.bm23.com/bta.js",function(err){if(err)return fn(err);var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);fn()})};Bronto.prototype.track=function(track){var revenue=track.revenue();var event=track.event();var type="number"==typeof revenue?"$":"t";this.bta.addConversionLegacy(type,event,revenue)};Bronto.prototype.completedOrder=function(track){var products=track.products();var props=track.properties();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addConversion({order_id:track.orderId(),date:props.date||new Date,items:items})}});require.register("segmentio-analytics.js-integrations/lib/bugherd.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(BugHerd)};var BugHerd=exports.Integration=integration("BugHerd").assumesPageview().readyOnLoad().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true);BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};this.load()};BugHerd.prototype.loaded=function(){return!!window._bugHerd};BugHerd.prototype.load=function(callback){load("//www.bugherd.com/sidebarv2.js?apikey="+this.options.apiKey,callback)}});require.register("segmentio-analytics.js-integrations/lib/bugsnag.js",function(exports,require,module){var integration=require("integration");var is=require("is");var extend=require("extend");var load=require("load-script");var onError=require("on-error");module.exports=exports=function(analytics){analytics.addIntegration(Bugsnag)};var Bugsnag=exports.Integration=integration("Bugsnag").readyOnLoad().global("Bugsnag").option("apiKey","");Bugsnag.prototype.initialize=function(page){this.load()};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.load=function(callback){var apiKey=this.options.apiKey;load("//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js",function(err){if(err)return callback(err);window.Bugsnag.apiKey=apiKey;callback()})};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}});require.register("segmentio-analytics.js-integrations/lib/chartbeat.js",function(exports,require,module){var integration=require("integration");var onBody=require("on-body");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Chartbeat)};var Chartbeat=exports.Integration=integration("Chartbeat").assumesPageview().readyOnLoad().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null);Chartbeat.prototype.initialize=function(page){window._sf_async_config=this.options;onBody(function(){window._sf_endpt=(new Date).getTime()});this.load()};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.load=function(callback){load({https:"https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js",http:"http://static.chartbeat.com/js/chartbeat.js"},callback)};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}});require.register("segmentio-analytics.js-integrations/lib/churnbee.js",function(exports,require,module){var push=require("global-queue")("_cbq");var integration=require("integration");var load=require("load-script");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};module.exports=exports=function(analytics){analytics.addIntegration(ChurnBee)};var ChurnBee=exports.Integration=integration("ChurnBee").readyOnInitialize().global("_cbq").global("ChurnBee").option("events",{}).option("apiKey","");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load()};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.load=function(fn){load("//api.churnbee.com/cb.js",fn)};ChurnBee.prototype.track=function(track){var events=this.options.events;var event=track.event();if(has.call(events,event))event=events[event];if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))}});require.register("segmentio-analytics.js-integrations/lib/clicktale.js",function(exports,require,module){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("integration");var is=require("is");var useHttps=require("use-https");var load=require("load-script");var onBody=require("on-body");module.exports=exports=function(analytics){analytics.addIntegration(ClickTale)};var ClickTale=exports.Integration=integration("ClickTale").assumesPageview().readyOnLoad().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","");ClickTale.prototype.initialize=function(page){var options=this.options;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});this.load(function(){window.ClickTale(options.projectId,options.recordingRatio,options.partitionId)})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.load=function(callback){var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");load({http:http,https:https},callback)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}});require.register("segmentio-analytics.js-integrations/lib/clicky.js",function(exports,require,module){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("integration");var is=require("is");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Clicky);user=analytics.user()};var Clicky=exports.Integration=integration("Clicky").assumesPageview().readyOnLoad().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null);Clicky.prototype.initialize=function(page){window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load()};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.load=function(callback){load("//static.getclicky.com/js",callback)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}});require.register("segmentio-analytics.js-integrations/lib/comscore.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Comscore)};var Comscore=exports.Integration=integration("comScore").assumesPageview().readyOnLoad().global("_comscore").global("COMSCORE").option("c1","2").option("c2","");Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];this.load()};Comscore.prototype.loaded=function(){return!!window.COMSCORE};Comscore.prototype.load=function(callback){load({http:"http://b.scorecardresearch.com/beacon.js",https:"https://sb.scorecardresearch.com/beacon.js"},callback)}});require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(CrazyEgg)};var CrazyEgg=exports.Integration=integration("Crazy Egg").assumesPageview().readyOnLoad().global("CE2").option("accountNumber","");CrazyEgg.prototype.initialize=function(page){this.load()};CrazyEgg.prototype.loaded=function(){return!!window.CE2};CrazyEgg.prototype.load=function(callback){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);var url="//dnn506yrbagrg.cloudfront.net/pages/scripts/"+path+".js?"+cache;load(url,callback)}});require.register("segmentio-analytics.js-integrations/lib/curebit.js",function(exports,require,module){var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var integration=require("integration");var iso=require("to-iso-string");var load=require("load-script");var push=require("global-queue")("_curebitq");var Track=require("facade").Track;var user;module.exports=exports=function(analytics){analytics.addIntegration(Curebit);user=analytics.user()};var Curebit=exports.Integration=integration("Curebit").readyOnInitialize().global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","").option("responsive",true).option("device","").option("insertIntoId","curebit-frame").option("campaigns",{}).option("server","https://www.curebit.com");Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load()};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.load=function(fn){var url="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js";load(url,fn)};Curebit.prototype.page=function(page){var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}});require.register("segmentio-analytics.js-integrations/lib/customerio.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(Customerio);user=analytics.user()};var Customerio=exports.Integration=integration("Customer.io").assumesPageview().readyOnInitialize().global("_cio").option("siteId","");Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load()};Customerio.prototype.loaded=function(){return!!(window._cio&&window._cio.pageHasLoaded)};Customerio.prototype.load=function(callback){var script=load("https://assets.customer.io/assets/track.js",callback);script.id="cio-tracker";script.setAttribute("data-site-id",this.options.siteId)};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}});require.register("segmentio-analytics.js-integrations/lib/drip.js",function(exports,require,module){var alias=require("alias");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");module.exports=exports=function(analytics){analytics.addIntegration(Drip)};var Drip=exports.Integration=integration("Drip").assumesPageview().readyOnLoad().global("dc").global("_dcq").global("_dcs").option("account","");Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load()};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.load=function(callback){load("//tag.getdrip.com/"+this.options.account+".js",callback)};Drip.prototype.track=function(track){var props=track.properties();var cents=Math.round(track.cents());props.action=track.event();if(cents)props.value=cents;delete props.revenue;push("track",props)}});require.register("segmentio-analytics.js-integrations/lib/errorception.js",function(exports,require,module){var callback=require("callback");var extend=require("extend");var integration=require("integration");var load=require("load-script");var onError=require("on-error");var push=require("global-queue")("_errs");module.exports=exports=function(analytics){analytics.addIntegration(Errorception)};var Errorception=exports.Integration=integration("Errorception").assumesPageview().readyOnInitialize().global("_errs").option("projectId","").option("meta",true);Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load()};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.load=function(callback){load("//beacon.errorception.com/"+this.options.projectId+".js",callback)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}});require.register("segmentio-analytics.js-integrations/lib/evergage.js",function(exports,require,module){var each=require("each");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_aaq");module.exports=exports=function(analytics){analytics.addIntegration(Evergage)};var Evergage=exports.Integration=integration("Evergage").assumesPageview().readyOnInitialize().global("_aaq").option("account","").option("dataset","");Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load()};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.load=function(callback){var account=this.options.account;var dataset=this.options.dataset;var url="//cdn.evergage.com/beacon/"+account+"/"+dataset+"/scripts/evergage.min.js";load(url,callback)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js",function(exports,require,module){var load=require("load-pixel")("//www.facebook.com/offsite_event.php");var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(Facebook)};exports.load=load;var has=Object.prototype.hasOwnProperty;var Facebook=exports.Integration=integration("Facebook Ads").readyOnInitialize().option("currency","USD").option("events",{});Facebook.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();if(!has.call(events,event))return;return exports.load({currency:this.options.currency,value:track.revenue()||0,id:events[event]})}});require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js",function(exports,require,module){var push=require("global-queue")("_fxm");var integration=require("integration");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(FoxMetrics)};var FoxMetrics=exports.Integration=integration("FoxMetrics").assumesPageview().readyOnInitialize().global("_fxm").option("appId","");FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load()};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.load=function(callback){var id=this.options.appId;load("//d35tca7vmefkrc.cloudfront.net/scripts/"+id+".js",callback)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");
var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}});require.register("segmentio-analytics.js-integrations/lib/frontleaf.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Frontleaf)};var Frontleaf=exports.Integration=integration("Frontleaf").assumesPageview().readyOnInitialize().global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","");Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);this.load()};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.load=function(fn){if(document.getElementById("_fl"))return callback.async(fn);var script=load(window._flBaseUrl+"/lib/tracker.js",fn);script.id="_fl"};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.track=function(track){var event=track.event();if(event){this._push("event",event,clean(track.properties()))}};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}});require.register("segmentio-analytics.js-integrations/lib/gauges.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_gauges");module.exports=exports=function(analytics){analytics.addIntegration(Gauges)};var Gauges=exports.Integration=integration("Gauges").assumesPageview().readyOnInitialize().global("_gauges").option("siteId","");Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load()};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.load=function(callback){var id=this.options.siteId;var script=load("//secure.gaug.es/track.js",callback);script.id="gauges-tracker";script.setAttribute("data-site-id",id)};Gauges.prototype.page=function(page){push("track")}});require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var onBody=require("on-body");module.exports=exports=function(analytics){analytics.addIntegration(GetSatisfaction)};var GetSatisfaction=exports.Integration=integration("Get Satisfaction").assumesPageview().readyOnLoad().global("GSFN").option("widgetId","");GetSatisfaction.prototype.initialize=function(page){var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id})})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN};GetSatisfaction.prototype.load=function(callback){load("https://loader.engage.gsfn.us/loader.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/google-analytics.js",function(exports,require,module){var callback=require("callback");var canonical=require("canonical");var each=require("each");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_gaq");var Track=require("facade").Track;var length=require("object").length;var keys=require("object").keys;var dot=require("obj-case");var type=require("type");var url=require("url");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",null).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{});GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.load=integration.loadClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;var gMetrics=metrics(group.traits(),opts);var uMetrics=metrics(user.traits(),opts);var custom;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","&uid",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);if(length(gMetrics))window.ga("set",gMetrics);if(length(uMetrics))window.ga("set",uMetrics);this.load()};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.load=function(callback){load("//www.google-analytics.com/analytics.js",callback)};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var pageview={};var track;this._category=category;var hit=metrics(page.properties(),this.options);hit.page=path(props,this.options);hit.title=name||props.title;hit.location=props.url;window.ga("send","pageview",hit);if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var event=metrics(props,this.options);event.eventAction=track.event();event.eventCategory=this._category||props.category||"All";event.eventLabel=props.label;event.eventValue=formatValue(props.value||track.revenue());event.nonInteraction=props.noninteraction||opts.noninteraction;window.ga("send","event",event)};GA.prototype.completedOrder=function(track){var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce","ecommerce.js");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:track.total(),tax:track.tax(),id:orderId});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}this.load()};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.loadClassic=function(callback){if(this.options.doubleClick){load("//stats.g.doubleclick.net/dc.js",callback)}else{load({http:"http://www.google-analytics.com/ga.js",https:"https://ssl.google-analytics.com/ga.js"},callback)}};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var orderId=track.orderId();var products=track.products()||[];var props=track.properties();if(!orderId)return;push("_addTrans",orderId,props.affiliation,track.total(),track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=metrics[names[i]]||dimensions[names[i]];var value=dot(obj,name);if(null==value)continue;ret[names[i]]=value}return ret}});require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js",function(exports,require,module){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(GTM)};var GTM=exports.Integration=integration("Google Tag Manager").assumesPageview().readyOnLoad().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true);GTM.prototype.initialize=function(){this.load()};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.load=function(fn){var id=this.options.containerId;push({"gtm.start":+new Date,event:"gtm.js"});load("//www.googletagmanager.com/gtm.js?id="+id+"&l=dataLayer",fn)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}});require.register("segmentio-analytics.js-integrations/lib/gosquared.js",function(exports,require,module){var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var integration=require("integration");var load=require("load-script");var onBody=require("on-body");var each=require("each");var user;module.exports=exports=function(analytics){analytics.addIntegration(GoSquared);user=analytics.user()};var GoSquared=exports.Integration=integration("GoSquared").assumesPageview().readyOnLoad().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true);GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load()};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.load=function(callback){load("//d1l6p2sc9645hc.cloudfront.net/tracker.js",callback)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}});require.register("segmentio-analytics.js-integrations/lib/heap.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Heap)};var Heap=exports.Integration=integration("Heap").assumesPageview().readyOnInitialize().global("heap").global("_heapid").option("apiKey","");Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load()};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.load=function(callback){load("//d36lvucg9kzous.cloudfront.net",callback)};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/hellobar.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Hellobar)};var Hellobar=exports.Integration=integration("Hello Bar").assumesPageview().readyOnInitialize().global("_hbq").option("apiKey","");Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load()};Hellobar.prototype.load=function(callback){var url="//s3.amazonaws.com/scripts.hellobar.com/"+this.options.apiKey+".js";load(url,callback)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}});require.register("segmentio-analytics.js-integrations/lib/hittail.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(HitTail)};var HitTail=exports.Integration=integration("HitTail").assumesPageview().readyOnLoad().global("htk").option("siteId","");HitTail.prototype.initialize=function(page){this.load()};HitTail.prototype.loaded=function(){return is.fn(window.htk)};HitTail.prototype.load=function(callback){var id=this.options.siteId;load("//"+id+".hittail.com/mlt.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/hubspot.js",function(exports,require,module){var callback=require("callback");var convert=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_hsq");module.exports=exports=function(analytics){analytics.addIntegration(HubSpot)};var HubSpot=exports.Integration=integration("HubSpot").assumesPageview().readyOnInitialize().global("_hsq").option("portalId",null);HubSpot.prototype.initialize=function(page){window._hsq=[];this.load()};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.load=function(fn){if(document.getElementById("hs-analytics"))return callback.async(fn);var id=this.options.portalId;var cache=Math.ceil(new Date/3e5)*3e5;var url="https://js.hs-analytics.net/analytics/"+cache+"/"+id+".js";var script=load(url,fn);script.id="hs-analytics"};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}});require.register("segmentio-analytics.js-integrations/lib/improvely.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Improvely)};var Improvely=exports.Integration=integration("Improvely").assumesPageview().readyOnInitialize().global("_improvely").global("improvely").option("domain","").option("projectId",null);Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load()};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.load=function(callback){var domain=this.options.domain;load("//"+domain+".iljmp.com/improvely.js",callback)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}});require.register("segmentio-analytics.js-integrations/lib/inspectlet.js",function(exports,require,module){var integration=require("integration");var alias=require("alias");var clone=require("clone");var load=require("load-script");var push=require("global-queue")("__insp");module.exports=exports=function(analytics){analytics.addIntegration(Inspectlet)};var Inspectlet=exports.Integration=integration("Inspectlet").assumesPageview().readyOnLoad().global("__insp").global("__insp_").option("wid","");Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load()};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.load=function(callback){load("//www.inspectlet.com/inspectlet.js",callback)};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}});require.register("segmentio-analytics.js-integrations/lib/intercom.js",function(exports,require,module){var alias=require("alias");var convertDates=require("convert-dates");var integration=require("integration");var each=require("each");var is=require("is");var isEmail=require("is-email");var load=require("load-script");var defaults=require("defaults");var empty=require("is-empty");var group;module.exports=exports=function(analytics){analytics.addIntegration(Intercom);group=analytics.group()};var Intercom=exports.Integration=integration("Intercom").assumesPageview().readyOnLoad().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false);Intercom.prototype.initialize=function(page){this.load()};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.load=function(callback){load("https://static.intercomcdn.com/intercom.v1.js",callback)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(!empty(group.traits())){traits.company=traits.company||{};defaults(traits.company,group.traits())}if(name)traits.name=name;if(companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company){traits.company=alias(traits.company,{created:"created_at"})}if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}});require.register("segmentio-analytics.js-integrations/lib/keen-io.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Keen)};var Keen=exports.Integration=integration("Keen IO").readyOnInitialize().global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true);Keen.prototype.initialize=function(){var options=this.options;window.Keen=window.Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};window.Keen.configure({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});this.load()};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.Base64)};Keen.prototype.load=function(callback){load("//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js",callback)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};if(id)user.userId=id;if(traits)user.traits=traits;window.Keen.setGlobalProperties(function(){return{user:user}})};Keen.prototype.track=function(track){window.Keen.addEvent(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/kenshoo.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Kenshoo)};var Kenshoo=exports.Integration=integration("Kenshoo").readyOnLoad().global("k_trackevent").option("cid","").option("subdomain","").option("trackNamedPages",true).option("trackCategorizedPages",true);Kenshoo.prototype.initialize=function(page){this.load()};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.load=function(callback){var url="//"+this.options.subdomain+".xg4ken.com/media/getpx.php?cid="+this.options.cid;load(url,callback)};Kenshoo.prototype.completedOrder=function(track){this._track(track,{val:track.total()})};Kenshoo.prototype.page=function(page){var category=page.category();var name=page.name();var fullName=page.fullName();var isNamed=name&&this.options.trackNamedPages;var isCategorized=category&&this.options.trackCategorizedPages;var track;if(name&&!this.options.trackNamedPages){return}if(category&&!this.options.trackCategorizedPages){return}if(isNamed&&isCategorized){track=page.track(fullName)}else if(isNamed){track=page.track(name)}else if(isCategorized){track=page.track(category)}else{track=page.track()}this._track(track)};Kenshoo.prototype.track=function(track){this._track(track)};Kenshoo.prototype._track=function(track,options){options=options||{val:track.revenue()};var params=["id="+this.options.cid,"type="+track.event(),"val="+(options.val||"0.0"),"orderId="+(track.orderId()||""),"promoCode="+(track.coupon()||""),"valueCurrency="+(track.currency()||""),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}});require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js",function(exports,require,module){var alias=require("alias");var Batch=require("batch");var callback=require("callback");var integration=require("integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(KISSmetrics)};var KISSmetrics=exports.Integration=integration("KISSmetrics").assumesPageview().readyOnInitialize().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackPages",true).option("prefixProperties",true);KISSmetrics.prototype.initialize=function(page){window._kmq=[];this.load()};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.load=function(callback){var key=this.options.apiKey;var useless="//i.kissmetrics.com/i.js";var library="//doug1izaerwt3.cloudfront.net/"+key+".1.js";(new Batch).push(function(done){load(useless,done)}).push(function(done){load(library,done)}).end(callback)};KISSmetrics.prototype.page=function(page){var name=page.fullName();var opts=this.options;if(name&&opts.trackPages){var track=page.track(name);this.track(track)}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var temp=new Track({event:event,properties:product});var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}});require.register("segmentio-analytics.js-integrations/lib/klaviyo.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_learnq");module.exports=exports=function(analytics){analytics.addIntegration(Klaviyo)};var Klaviyo=exports.Integration=integration("Klaviyo").assumesPageview().readyOnInitialize().global("_learnq").option("apiKey","");Klaviyo.prototype.initialize=function(page){push("account",this.options.apiKey);this.load()};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.load=function(callback){load("//a.klaviyo.com/media/js/learnmarklet.js",callback)};var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}});require.register("segmentio-analytics.js-integrations/lib/leadlander.js",function(exports,require,module){var integration=require("integration");
var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(LeadLander)};var LeadLander=exports.Integration=integration("LeadLander").assumesPageview().readyOnLoad().global("llactid").global("trackalyzer").option("accountId",null);LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load()};LeadLander.prototype.loaded=function(){return!!window.trackalyzer};LeadLander.prototype.load=function(callback){load("http://t6.trackalyzer.com/trackalyze-nodoc.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/livechat.js",function(exports,require,module){var each=require("each");var integration=require("integration");var load=require("load-script");var clone=require("clone");var when=require("when");module.exports=exports=function(analytics){analytics.addIntegration(LiveChat)};var LiveChat=exports.Integration=integration("LiveChat").assumesPageview().readyOnLoad().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","");LiveChat.prototype.initialize=function(page){window.__lc=clone(this.options);this.load()};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.load=function(callback){var self=this;load("//cdn.livechatinc.com/tracking.js",function(err){if(err)return callback(err);when(function(){return self.loaded()},callback)})};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}});require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js",function(exports,require,module){var Identify=require("facade").Identify;var integration=require("integration");var load=require("load-script");var user;module.exports=exports=function(analytics){analytics.addIntegration(LuckyOrange);user=analytics.user()};var LuckyOrange=exports.Integration=integration("Lucky Orange").assumesPageview().readyOnLoad().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null);LuckyOrange.prototype.initialize=function(page){window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));this.load()};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.load=function(callback){var cache=Math.floor((new Date).getTime()/6e4);load({http:"http://www.luckyorange.com/w.js?"+cache,https:"https://ssl.luckyorange.com/w.js?"+cache},callback)};LuckyOrange.prototype.identify=function(identify){var traits=window.__wtw_custom_user_data=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email}});require.register("segmentio-analytics.js-integrations/lib/lytics.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Lytics)};var Lytics=exports.Integration=integration("Lytics").readyOnInitialize().global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io");var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load()};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.load=function(callback){load("//c.lytics.io/static/io.min.js",callback)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}});require.register("segmentio-analytics.js-integrations/lib/mixpanel.js",function(exports,require,module){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("integration");var iso=require("to-iso-string");var load=require("load-script");var indexof=require("indexof");var del=require("obj-case").del;module.exports=exports=function(analytics){analytics.addIntegration(Mixpanel)};var Mixpanel=exports.Integration=integration("Mixpanel").readyOnLoad().global("mixpanel").option("increments",[]).option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true);var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load()};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.load=function(callback){load("//cdn.mxpnl.com/libs/mixpanel-2.2.min.js",callback)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(traits);if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}});require.register("segmentio-analytics.js-integrations/lib/mojn.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Mojn)};var Mojn=exports.Integration=integration("Mojn").option("customerCode","").global("_mojnTrack").readyOnInitialize();Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});this.load()};Mojn.prototype.load=function(fn){load("https://track.idtargeting.com/"+this.options.customerCode+"/track.js",fn)};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}});require.register("segmentio-analytics.js-integrations/lib/mouseflow.js",function(exports,require,module){var push=require("global-queue")("_mfq");var integration=require("integration");var load=require("load-script");var each=require("each");module.exports=exports=function(analytics){analytics.addIntegration(Mouseflow)};var Mouseflow=exports.Integration=integration("Mouseflow").assumesPageview().readyOnLoad().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0);Mouseflow.prototype.initialize=function(page){this.load()};Mouseflow.prototype.loaded=function(){return!!(window._mfq&&[].push!=window._mfq.push)};Mouseflow.prototype.load=function(fn){var apiKey=this.options.apiKey;window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;load("//cdn.mouseflow.com/projects/"+apiKey+".js",fn)};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(hash){each(hash,function(k,v){push("setVariable",k,v)})}});require.register("segmentio-analytics.js-integrations/lib/mousestats.js",function(exports,require,module){var each=require("each");var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(MouseStats)};var MouseStats=exports.Integration=integration("MouseStats").assumesPageview().readyOnLoad().global("msaa").option("accountNumber","");MouseStats.prototype.initialize=function(page){this.load()};MouseStats.prototype.loaded=function(){return is.fn(window.msaa)};MouseStats.prototype.load=function(callback){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var partial=".mousestats.com/js/"+path+".js?"+cache;var http="http://www2"+partial;var https="https://ssl"+partial;load({http:http,https:https},callback)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}});require.register("segmentio-analytics.js-integrations/lib/navilytics.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var push=require("global-queue")("__nls");module.exports=exports=function(analytics){analytics.addIntegration(Navilytics)};var Navilytics=exports.Integration=integration("Navilytics").assumesPageview().readyOnLoad().global("__nls").option("memberId","").option("projectId","");Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load()};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.load=function(callback){var mid=this.options.memberId;var pid=this.options.projectId;var url="//www.navilytics.com/nls.js?mid="+mid+"&pid="+pid;load(url,callback)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}});require.register("segmentio-analytics.js-integrations/lib/olark.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var https=require("use-https");module.exports=exports=function(analytics){analytics.addIntegration(Olark)};var Olark=exports.Integration=integration("Olark").assumesPageview().readyOnInitialize().global("olark").option("identify",true).option("page",true).option("siteId","").option("track",false);Olark.prototype.initialize=function(page){window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);var self=this;box("onExpand",function(){self._open=true});box("onShrink",function(){self._open=false})};Olark.prototype.page=function(page){if(!this.options.page||!this._open)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;var msg=name?name.toLowerCase()+" page":props.url;chat("sendNotificationToOperator",{body:"looking at "+msg})};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();visitor("updateCustomFields",traits);if(email)visitor("updateEmailAddress",{emailAddress:email});if(phone)visitor("updatePhoneNumber",{phoneNumber:phone});if(name)visitor("updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)chat("updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track||!this._open)return;chat("sendNotificationToOperator",{body:'visitor triggered "'+track.event()+'"'})};function box(action,value){window.olark("api.box."+action,value)}function visitor(action,value){window.olark("api.visitor."+action,value)}function chat(action,value){window.olark("api.chat."+action,value)}});require.register("segmentio-analytics.js-integrations/lib/optimizely.js",function(exports,require,module){var bind=require("bind");var callback=require("callback");var each=require("each");var integration=require("integration");var push=require("global-queue")("optimizely");var tick=require("next-tick");var analytics;module.exports=exports=function(ajs){ajs.addIntegration(Optimizely);analytics=ajs};var Optimizely=exports.Integration=integration("Optimizely").readyOnInitialize().option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations)tick(this.replay)};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});analytics.identify(traits)}});require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(PerfectAudience)};var PerfectAudience=exports.Integration=integration("Perfect Audience").assumesPageview().readyOnLoad().global("_pa").option("siteId","");PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load()};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.load=function(callback){var id=this.options.siteId;load("//tag.perfectaudience.com/serve/"+id+".js",callback)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/pingdom.js",function(exports,require,module){var date=require("load-date");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_prum");module.exports=exports=function(analytics){analytics.addIntegration(Pingdom)};var Pingdom=exports.Integration=integration("Pingdom").assumesPageview().readyOnLoad().global("_prum").option("id","");Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());this.load()};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)};Pingdom.prototype.load=function(callback){load("//rum-static.pingdom.net/prum.min.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/piwik.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_paq");module.exports=exports=function(analytics){analytics.addIntegration(Piwik)};var Piwik=exports.Integration=integration("Piwik").global("_paq").option("url",null).option("siteId","").assumesPageview().readyOnInitialize();Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load()};Piwik.prototype.load=function(callback){load(this.options.url+"/piwik.js",callback)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")}});require.register("segmentio-analytics.js-integrations/lib/preact.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_lnq");module.exports=exports=function(analytics){analytics.addIntegration(Preact)};var Preact=exports.Integration=integration("Preact").assumesPageview().readyOnInitialize().global("_lnq").option("projectCode","");Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load()};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.load=function(callback){load("//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js",callback)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}});require.register("segmentio-analytics.js-integrations/lib/qualaroo.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;module.exports=exports=function(analytics){analytics.addIntegration(Qualaroo)};var Qualaroo=exports.Integration=integration("Qualaroo").assumesPageview().readyOnInitialize().global("_kiq").option("customerId","").option("siteToken","").option("track",false);Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];this.load()};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.load=function(callback){var token=this.options.siteToken;var id=this.options.customerId;load("//s3.amazonaws.com/ki.js/"+id+"/"+token+".js",callback)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}});require.register("segmentio-analytics.js-integrations/lib/quantcast.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_qevents",{wrap:false});var user;module.exports=exports=function(analytics){analytics.addIntegration(Quantcast);user=analytics.user()};var Quantcast=exports.Integration=integration("Quantcast").assumesPageview().readyOnInitialize().global("_qevents").global("__qc").option("pCode",null).option("advertise",false);Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};if(user.id())settings.uid=user.id();if(page){settings.labels=this.labels("page",page.category(),page.name())}push(settings);this.load()};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.load=function(callback){load({http:"http://edge.quantserve.com/quant.js",https:"https://secure.quantserve.com/quant.js"},callback)};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var settings={event:"refresh",labels:this.labels("page",category,name),qacct:this.options.pCode};if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id)window._qevents[0].uid=id};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var settings={event:"click",labels:this.labels("event",name),qacct:this.options.pCode};if(null!=revenue)settings.revenue=revenue+"";if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var labels=this.labels("event",name);var category=track.category();if(this.options.advertise&&category){labels+=","+this.labels("pcat",category)}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype.labels=function(type){var args=[].slice.call(arguments,1);var advertise=this.options.advertise;var ret=[];if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;for(var i=0;i<args.length;++i){if(null==args[i])continue;var value=String(args[i]);ret.push(value.replace(/,/g,";"))}ret=advertise?ret.join(" "):ret.join(".");return[type,ret].join(".")}});require.register("segmentio-analytics.js-integrations/lib/rollbar.js",function(exports,require,module){var integration=require("integration");var is=require("is");var extend=require("extend");module.exports=exports=function(analytics){analytics.addIntegration(RollbarIntegration)};var RollbarIntegration=exports.Integration=integration("Rollbar").readyOnInitialize().global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};!function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)}(window,document);this.load()};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}});require.register("segmentio-analytics.js-integrations/lib/saasquatch.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(SaaSquatch)};var SaaSquatch=exports.Integration=integration("SaaSquatch").readyOnInitialize().option("tenantAlias","").global("_sqh");SaaSquatch.prototype.initialize=function(page){};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.load=function(fn){load("//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js",fn)};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh=window._sqh||[];var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}});require.register("segmentio-analytics.js-integrations/lib/sentry.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Sentry)};var Sentry=exports.Integration=integration("Sentry").readyOnLoad().global("Raven").option("config","");Sentry.prototype.initialize=function(){var config=this.options.config;this.load(function(){window.Raven.config(config).install()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.load=function(callback){load("//cdn.ravenjs.com/1.1.10/native/raven.min.js",callback)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}});require.register("segmentio-analytics.js-integrations/lib/snapengage.js",function(exports,require,module){var integration=require("integration");var is=require("is");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(SnapEngage)};var SnapEngage=exports.Integration=integration("SnapEngage").assumesPageview().readyOnLoad().global("SnapABug").option("apiKey","");SnapEngage.prototype.initialize=function(page){this.load()};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.load=function(callback){var key=this.options.apiKey;var url="//commondatastorage.googleapis.com/code.snapengage.com/js/"+key+".js";load(url,callback)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;
window.SnapABug.setUserEmail(email)}});require.register("segmentio-analytics.js-integrations/lib/spinnakr.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Spinnakr)};var Spinnakr=exports.Integration=integration("Spinnakr").assumesPageview().readyOnLoad().global("_spinnakr_site_id").global("_spinnakr").option("siteId","");Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;this.load()};Spinnakr.prototype.loaded=function(){return!!window._spinnakr};Spinnakr.prototype.load=function(callback){load("//d3ojzyhbolvoi5.cloudfront.net/js/so.js",callback)}});require.register("segmentio-analytics.js-integrations/lib/tapstream.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var slug=require("slug");var push=require("global-queue")("_tsq");module.exports=exports=function(analytics){analytics.addIntegration(Tapstream)};var Tapstream=exports.Integration=integration("Tapstream").assumesPageview().readyOnInitialize().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load()};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.load=function(callback){load("//cdn.tapstream.com/static/js/tapstream.js",callback)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}});require.register("segmentio-analytics.js-integrations/lib/trakio.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var clone=require("clone");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Trakio)};var Trakio=exports.Integration=integration("trak.io").assumesPageview().readyOnInitialize().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true);var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var self=this;var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.io.load=function(e){self.load();var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load()};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.load=function(callback){load("//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js",callback)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}});require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js",function(exports,require,module){var pixel=require("load-pixel")("//analytics.twitter.com/i/adsct");var integration=require("integration");module.exports=exports=function(analytics){analytics.addIntegration(TwitterAds)};exports.load=pixel;var has=Object.prototype.hasOwnProperty;var TwitterAds=exports.Integration=integration("Twitter Ads").readyOnInitialize().option("events",{});TwitterAds.prototype.track=function(track){var events=this.options.events;var event=track.event();if(!has.call(events,event))return;return exports.load({txn_id:events[event],p_id:"Twitter"})}});require.register("segmentio-analytics.js-integrations/lib/usercycle.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_uc");module.exports=exports=function(analytics){analytics.addIntegration(Usercycle)};var Usercycle=exports.Integration=integration("USERcycle").assumesPageview().readyOnInitialize().global("_uc").option("key","");Usercycle.prototype.initialize=function(page){push("_key",this.options.key);this.load()};Usercycle.prototype.loaded=function(){return!!(window._uc&&window._uc.push!==Array.prototype.push)};Usercycle.prototype.load=function(callback){load("//api.usercycle.com/javascripts/track.js",callback)};Usercycle.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("uid",id);push("action","came_back",traits)};Usercycle.prototype.track=function(track){push("action",track.event(),track.properties({revenue:"revenue_amount"}))}});require.register("segmentio-analytics.js-integrations/lib/userfox.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_ufq");module.exports=exports=function(analytics){analytics.addIntegration(Userfox)};var Userfox=exports.Integration=integration("userfox").assumesPageview().readyOnInitialize().global("_ufq").option("clientId","");Userfox.prototype.initialize=function(page){window._ufq=[];this.load()};Userfox.prototype.loaded=function(){return!!(window._ufq&&window._ufq.push!==Array.prototype.push)};Userfox.prototype.load=function(callback){load("//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js",callback)};Userfox.prototype.identify=function(identify){var traits=identify.traits({created:"signup_date"});var email=identify.email();if(!email)return;push("init",{clientId:this.options.clientId,email:email});traits=convertDates(traits,formatDate);push("track",traits)};function formatDate(date){return Math.round(date.getTime()/1e3).toString()}});require.register("segmentio-analytics.js-integrations/lib/uservoice.js",function(exports,require,module){var alias=require("alias");var callback=require("callback");var clone=require("clone");var convertDates=require("convert-dates");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("UserVoice");var unix=require("to-unix-timestamp");module.exports=exports=function(analytics){analytics.addIntegration(UserVoice)};var UserVoice=exports.Integration=integration("UserVoice").assumesPageview().readyOnInitialize().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false);UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load()};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.load=function(callback){var key=this.options.apiKey;load("//widget.uservoice.com/"+key+".js",callback)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load()};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}});require.register("segmentio-analytics.js-integrations/lib/vero.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");var push=require("global-queue")("_veroq");module.exports=exports=function(analytics){analytics.addIntegration(Vero)};var Vero=exports.Integration=integration("Vero").readyOnInitialize().global("_veroq").option("apiKey","");Vero.prototype.initialize=function(pgae){push("init",{api_key:this.options.apiKey});this.load()};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.load=function(callback){load("//d3qxef4rp70elm.cloudfront.net/m.js",callback)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js",function(exports,require,module){var callback=require("callback");var each=require("each");var integration=require("integration");var tick=require("next-tick");var analytics;module.exports=exports=function(ajs){ajs.addIntegration(VWO);analytics=ajs};var VWO=exports.Integration=integration("Visual Website Optimizer").readyOnInitialize().option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay()};VWO.prototype.replay=function(){tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(callback){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return callback();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});callback(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}});require.register("segmentio-analytics.js-integrations/lib/webengage.js",function(exports,require,module){var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(WebEngage)};var WebEngage=exports.Integration=integration("WebEngage").assumesPageview().readyOnLoad().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","");WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;this.load()};WebEngage.prototype.loaded=function(){return!!window.webengage};WebEngage.prototype.load=function(fn){var path="/js/widget/webengage-min-v-4.0.js";load({https:"https://ssl.widgets.webengage.com"+path,http:"http://cdn.widgets.webengage.com"+path},fn)}});require.register("segmentio-analytics.js-integrations/lib/woopra.js",function(exports,require,module){var each=require("each");var extend=require("extend");var integration=require("integration");var isEmail=require("is-email");var load=require("load-script");var type=require("type");module.exports=exports=function(analytics){analytics.addIntegration(Woopra)};var Woopra=exports.Integration=integration("Woopra").readyOnLoad().global("woopra").option("domain","");Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");window.woopra.config({domain:this.options.domain});this.load()};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.load=function(callback){load("//static.woopra.com/js/w.js",callback)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){window.woopra.identify(identify.traits()).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}});require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js",function(exports,require,module){var callback=require("callback");var integration=require("integration");var load=require("load-script");module.exports=exports=function(analytics){analytics.addIntegration(Yandex)};var Yandex=exports.Integration=integration("Yandex Metrica").assumesPageview().readyOnInitialize().global("yandex_metrika_callbacks").global("Ya").option("counterId",null);Yandex.prototype.initialize=function(page){var id=this.options.counterId;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id})});this.load()};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};Yandex.prototype.load=function(callback){load("//mc.yandex.ru/metrika/watch.js",callback)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}});require.register("segmentio-canonical/index.js",function(exports,require,module){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}});require.register("segmentio-extend/index.js",function(exports,require,module){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}});require.register("camshaft-require-component/index.js",function(exports,require,module){module.exports=function(parent){function require(name,fallback){try{return parent(name)}catch(e){try{return parent(fallback||name+"-component")}catch(e2){throw e}}}for(var key in parent){require[key]=parent[key]}return require}});require.register("segmentio-facade/lib/index.js",function(exports,require,module){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")});require.register("segmentio-facade/lib/alias.js",function(exports,require,module){var Facade=require("./facade");var component=require("require-component")(require);var inherit=component("inherit");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}});require.register("segmentio-facade/lib/facade.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var isEnabled=component("./is-enabled");var objCase=component("obj-case");var traverse=component("isodate-traverse");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=new Date(obj.timestamp);this.obj=obj}Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.prototype.json=function(){return clone(this.obj)};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);traverse(cloned);return cloned}});require.register("segmentio-facade/lib/group.js",function(exports,require,module){var Facade=require("./facade");var component=require("require-component")(require);var inherit=component("inherit");var newDate=component("new-date");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}});require.register("segmentio-facade/lib/page.js",function(exports,require,module){var component=require("require-component")(require);var Facade=component("./facade");var inherit=component("inherit");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),properties:props})}});require.register("segmentio-facade/lib/identify.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var Facade=component("./facade");var inherit=component("inherit");var isEmail=component("is-email");var newDate=component("new-date");var trim=component("trim");module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.proxy("traits.website");Identify.prototype.phone=Facade.proxy("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.avatar=Facade.proxy("traits.avatar")});require.register("segmentio-facade/lib/is-enabled.js",function(exports,require,module){var disabled={Salesforce:true,Marketo:true};module.exports=function(integration){return!disabled[integration]}});require.register("segmentio-facade/lib/track.js",function(exports,require,module){var component=require("require-component")(require);var clone=component("clone");var Facade=component("./facade");var Identify=component("./identify");var inherit=component("inherit");var isEmail=component("is-email");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.country=Facade.proxy("properties.country");Track.prototype.state=Facade.proxy("properties.state");Track.prototype.city=Facade.proxy("properties.city");Track.prototype.zip=Facade.proxy("properties.zip");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=this.obj.properties.subtotal;var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;return total};Track.prototype.products=function(){var props=this.obj.properties||{};return props.products||[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.traits=function(){return this.proxy("options.traits")||{}};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}});require.register("segmentio-facade/lib/screen.js",function(exports,require,module){var component=require("require-component")(require);var inherit=component("inherit");var Page=component("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),properties:props})}});require.register("segmentio-is-email/index.js",function(exports,require,module){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}});require.register("segmentio-is-meta/index.js",function(exports,require,module){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}});require.register("segmentio-isodate/index.js",function(exports,require,module){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,8,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;if(arr[8])arr[8]=(arr[8]+"00").substring(0,3);if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}});require.register("segmentio-isodate-traverse/index.js",function(exports,require,module){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input)){return object(input,strict)}else if(is.array(input)){return array(input,strict)}}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}});require.register("component-json-fallback/index.js",function(exports,require,module){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null
};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()});require.register("segmentio-json/index.js",function(exports,require,module){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")});require.register("segmentio-new-date/lib/index.js",function(exports,require,module){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}});require.register("segmentio-new-date/lib/milliseconds.js",function(exports,require,module){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}});require.register("segmentio-new-date/lib/seconds.js",function(exports,require,module){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}});require.register("segmentio-store.js/store.js",function(exports,require,module){(function(win){var store={},doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return JSON.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return JSON.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;if(typeof module!="undefined"&&module.exports){module.exports=store}else if(typeof define==="function"&&define.amd){define(store)}else{win.store=store}})(this.window||global)});require.register("segmentio-top-domain/index.js",function(exports,require,module){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}});require.register("visionmedia-debug/index.js",function(exports,require,module){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}});require.register("visionmedia-debug/debug.js",function(exports,require,module){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}});require.register("yields-prevent/index.js",function(exports,require,module){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}});require.register("analytics/lib/index.js",function(exports,require,module){var Integrations=require("integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION="1.5.0";each(Integrations,function(name,Integration){analytics.use(Integration)})});require.register("analytics/lib/analytics.js",function(exports,require,module){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;module.exports=Analytics;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;this._integrations={};user.load();group.load();var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});var ready=after(size(settings),function(){self._readied=true;self.emit("ready")});each(settings,function(name,opts){var Integration=self.Integrations[name];if(options.initialPageview&&opts.initialPageview===false){Integration.prototype.page=after(2,Integration.prototype.page)}var integration=new Integration(clone(opts));integration.once("ready",ready);integration.initialize();self._integrations[name]=integration});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",new Identify({options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",new Group({options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",new Track({properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);properties.url=properties.url||canonicalUrl(properties.search);this._invoke("page",new Page({properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",new Alias({options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}});require.register("analytics/lib/cookie.js",function(exports,require,module){var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);if("."==domain)domain="";defaults(options,{maxage:31536e6,path:"/",domain:domain});this._options=options};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie});require.register("analytics/lib/entity.js",function(exports,require,module){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options)}Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var ret=this._options.persist?cookie.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){cookie.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}});require.register("analytics/lib/group.js",function(exports,require,module){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group});require.register("analytics/lib/store.js",function(exports,require,module){var bind=require("bind");var defaults=require("defaults");var store=require("store");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store});require.register("analytics/lib/user.js",function(exports,require,module){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User});require.register("segmentio-analytics.js-integrations/lib/slugs.json",function(exports,require,module){module.exports=["adroll","adwords","alexa","amplitude","awesm","awesomatic","bing-ads","bronto","bugherd","bugsnag","chartbeat","churnbee","clicktale","clicky","comscore","crazy-egg","curebit","customerio","drip","errorception","evergage","facebook-ads","foxmetrics","frontleaf","gauges","get-satisfaction","google-analytics","google-tag-manager","gosquared","heap","hellobar","hittail","hubspot","improvely","inspectlet","intercom","keen-io","kenshoo","kissmetrics","klaviyo","leadlander","livechat","lucky-orange","lytics","mixpanel","mojn","mouseflow","mousestats","navilytics","olark","optimizely","perfect-audience","pingdom","piwik","preact","qualaroo","quantcast","rollbar","saasquatch","sentry","snapengage","spinnakr","tapstream","trakio","twitter-ads","usercycle","userfox","uservoice","vero","visual-website-optimizer","webengage","woopra","yandex-metrica"]});require.alias("avetisk-defaults/index.js","analytics/deps/defaults/index.js");require.alias("avetisk-defaults/index.js","defaults/index.js");require.alias("component-clone/index.js","analytics/deps/clone/index.js");require.alias("component-clone/index.js","clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-cookie/index.js","analytics/deps/cookie/index.js");require.alias("component-cookie/index.js","cookie/index.js");require.alias("component-each/index.js","analytics/deps/each/index.js");require.alias("component-each/index.js","each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("component-emitter/index.js","analytics/deps/emitter/index.js");require.alias("component-emitter/index.js","emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("component-event/index.js","analytics/deps/event/index.js");require.alias("component-event/index.js","event/index.js");require.alias("component-inherit/index.js","analytics/deps/inherit/index.js");require.alias("component-inherit/index.js","inherit/index.js");require.alias("component-object/index.js","analytics/deps/object/index.js");require.alias("component-object/index.js","object/index.js");require.alias("component-querystring/index.js","analytics/deps/querystring/index.js");require.alias("component-querystring/index.js","querystring/index.js");require.alias("component-trim/index.js","component-querystring/deps/trim/index.js");require.alias("component-type/index.js","component-querystring/deps/type/index.js");require.alias("component-url/index.js","analytics/deps/url/index.js");require.alias("component-url/index.js","url/index.js");require.alias("ianstormtaylor-bind/index.js","analytics/deps/bind/index.js");require.alias("ianstormtaylor-bind/index.js","bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","analytics/deps/callback/index.js");require.alias("ianstormtaylor-callback/index.js","callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("ianstormtaylor-is/index.js","analytics/deps/is/index.js");require.alias("ianstormtaylor-is/index.js","is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-after/index.js","analytics/deps/after/index.js");require.alias("segmentio-after/index.js","after/index.js");require.alias("segmentio-analytics.js-integrations/index.js","analytics/deps/integrations/index.js");require.alias("segmentio-analytics.js-integrations/lib/adroll.js","analytics/deps/integrations/lib/adroll.js");require.alias("segmentio-analytics.js-integrations/lib/adwords.js","analytics/deps/integrations/lib/adwords.js");require.alias("segmentio-analytics.js-integrations/lib/alexa.js","analytics/deps/integrations/lib/alexa.js");require.alias("segmentio-analytics.js-integrations/lib/amplitude.js","analytics/deps/integrations/lib/amplitude.js");require.alias("segmentio-analytics.js-integrations/lib/awesm.js","analytics/deps/integrations/lib/awesm.js");require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js","analytics/deps/integrations/lib/awesomatic.js");require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js","analytics/deps/integrations/lib/bing-ads.js");require.alias("segmentio-analytics.js-integrations/lib/bronto.js","analytics/deps/integrations/lib/bronto.js");require.alias("segmentio-analytics.js-integrations/lib/bugherd.js","analytics/deps/integrations/lib/bugherd.js");require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js","analytics/deps/integrations/lib/bugsnag.js");require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js","analytics/deps/integrations/lib/chartbeat.js");require.alias("segmentio-analytics.js-integrations/lib/churnbee.js","analytics/deps/integrations/lib/churnbee.js");require.alias("segmentio-analytics.js-integrations/lib/clicktale.js","analytics/deps/integrations/lib/clicktale.js");require.alias("segmentio-analytics.js-integrations/lib/clicky.js","analytics/deps/integrations/lib/clicky.js");require.alias("segmentio-analytics.js-integrations/lib/comscore.js","analytics/deps/integrations/lib/comscore.js");require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js","analytics/deps/integrations/lib/crazy-egg.js");require.alias("segmentio-analytics.js-integrations/lib/curebit.js","analytics/deps/integrations/lib/curebit.js");require.alias("segmentio-analytics.js-integrations/lib/customerio.js","analytics/deps/integrations/lib/customerio.js");require.alias("segmentio-analytics.js-integrations/lib/drip.js","analytics/deps/integrations/lib/drip.js");require.alias("segmentio-analytics.js-integrations/lib/errorception.js","analytics/deps/integrations/lib/errorception.js");require.alias("segmentio-analytics.js-integrations/lib/evergage.js","analytics/deps/integrations/lib/evergage.js");require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js","analytics/deps/integrations/lib/facebook-ads.js");require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js","analytics/deps/integrations/lib/foxmetrics.js");require.alias("segmentio-analytics.js-integrations/lib/frontleaf.js","analytics/deps/integrations/lib/frontleaf.js");require.alias("segmentio-analytics.js-integrations/lib/gauges.js","analytics/deps/integrations/lib/gauges.js");require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js","analytics/deps/integrations/lib/get-satisfaction.js");require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js","analytics/deps/integrations/lib/google-analytics.js");require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js","analytics/deps/integrations/lib/google-tag-manager.js");require.alias("segmentio-analytics.js-integrations/lib/gosquared.js","analytics/deps/integrations/lib/gosquared.js");require.alias("segmentio-analytics.js-integrations/lib/heap.js","analytics/deps/integrations/lib/heap.js");require.alias("segmentio-analytics.js-integrations/lib/hellobar.js","analytics/deps/integrations/lib/hellobar.js");require.alias("segmentio-analytics.js-integrations/lib/hittail.js","analytics/deps/integrations/lib/hittail.js");require.alias("segmentio-analytics.js-integrations/lib/hubspot.js","analytics/deps/integrations/lib/hubspot.js");require.alias("segmentio-analytics.js-integrations/lib/improvely.js","analytics/deps/integrations/lib/improvely.js");require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js","analytics/deps/integrations/lib/inspectlet.js");require.alias("segmentio-analytics.js-integrations/lib/intercom.js","analytics/deps/integrations/lib/intercom.js");require.alias("segmentio-analytics.js-integrations/lib/keen-io.js","analytics/deps/integrations/lib/keen-io.js");require.alias("segmentio-analytics.js-integrations/lib/kenshoo.js","analytics/deps/integrations/lib/kenshoo.js");require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js","analytics/deps/integrations/lib/kissmetrics.js");require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js","analytics/deps/integrations/lib/klaviyo.js");require.alias("segmentio-analytics.js-integrations/lib/leadlander.js","analytics/deps/integrations/lib/leadlander.js");require.alias("segmentio-analytics.js-integrations/lib/livechat.js","analytics/deps/integrations/lib/livechat.js");require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js","analytics/deps/integrations/lib/lucky-orange.js");require.alias("segmentio-analytics.js-integrations/lib/lytics.js","analytics/deps/integrations/lib/lytics.js");
require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js","analytics/deps/integrations/lib/mixpanel.js");require.alias("segmentio-analytics.js-integrations/lib/mojn.js","analytics/deps/integrations/lib/mojn.js");require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js","analytics/deps/integrations/lib/mouseflow.js");require.alias("segmentio-analytics.js-integrations/lib/mousestats.js","analytics/deps/integrations/lib/mousestats.js");require.alias("segmentio-analytics.js-integrations/lib/navilytics.js","analytics/deps/integrations/lib/navilytics.js");require.alias("segmentio-analytics.js-integrations/lib/olark.js","analytics/deps/integrations/lib/olark.js");require.alias("segmentio-analytics.js-integrations/lib/optimizely.js","analytics/deps/integrations/lib/optimizely.js");require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js","analytics/deps/integrations/lib/perfect-audience.js");require.alias("segmentio-analytics.js-integrations/lib/pingdom.js","analytics/deps/integrations/lib/pingdom.js");require.alias("segmentio-analytics.js-integrations/lib/piwik.js","analytics/deps/integrations/lib/piwik.js");require.alias("segmentio-analytics.js-integrations/lib/preact.js","analytics/deps/integrations/lib/preact.js");require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js","analytics/deps/integrations/lib/qualaroo.js");require.alias("segmentio-analytics.js-integrations/lib/quantcast.js","analytics/deps/integrations/lib/quantcast.js");require.alias("segmentio-analytics.js-integrations/lib/rollbar.js","analytics/deps/integrations/lib/rollbar.js");require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js","analytics/deps/integrations/lib/saasquatch.js");require.alias("segmentio-analytics.js-integrations/lib/sentry.js","analytics/deps/integrations/lib/sentry.js");require.alias("segmentio-analytics.js-integrations/lib/snapengage.js","analytics/deps/integrations/lib/snapengage.js");require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js","analytics/deps/integrations/lib/spinnakr.js");require.alias("segmentio-analytics.js-integrations/lib/tapstream.js","analytics/deps/integrations/lib/tapstream.js");require.alias("segmentio-analytics.js-integrations/lib/trakio.js","analytics/deps/integrations/lib/trakio.js");require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js","analytics/deps/integrations/lib/twitter-ads.js");require.alias("segmentio-analytics.js-integrations/lib/usercycle.js","analytics/deps/integrations/lib/usercycle.js");require.alias("segmentio-analytics.js-integrations/lib/userfox.js","analytics/deps/integrations/lib/userfox.js");require.alias("segmentio-analytics.js-integrations/lib/uservoice.js","analytics/deps/integrations/lib/uservoice.js");require.alias("segmentio-analytics.js-integrations/lib/vero.js","analytics/deps/integrations/lib/vero.js");require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js","analytics/deps/integrations/lib/visual-website-optimizer.js");require.alias("segmentio-analytics.js-integrations/lib/webengage.js","analytics/deps/integrations/lib/webengage.js");require.alias("segmentio-analytics.js-integrations/lib/woopra.js","analytics/deps/integrations/lib/woopra.js");require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js","analytics/deps/integrations/lib/yandex-metrica.js");require.alias("segmentio-analytics.js-integrations/index.js","integrations/index.js");require.alias("avetisk-defaults/index.js","segmentio-analytics.js-integrations/deps/defaults/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integrations/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-domify/index.js","segmentio-analytics.js-integrations/deps/domify/index.js");require.alias("component-each/index.js","segmentio-analytics.js-integrations/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("component-once/index.js","segmentio-analytics.js-integrations/deps/once/index.js");require.alias("component-type/index.js","segmentio-analytics.js-integrations/deps/type/index.js");require.alias("component-url/index.js","segmentio-analytics.js-integrations/deps/url/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integrations/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integrations/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-analytics.js-integrations/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("ianstormtaylor-is-empty/index.js","segmentio-analytics.js-integrations/deps/is-empty/index.js");require.alias("segmentio-alias/index.js","segmentio-analytics.js-integrations/deps/alias/index.js");require.alias("component-clone/index.js","segmentio-alias/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-type/index.js","segmentio-alias/deps/type/index.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integrations/deps/integration/lib/index.js");require.alias("segmentio-analytics.js-integration/lib/protos.js","segmentio-analytics.js-integrations/deps/integration/lib/protos.js");require.alias("segmentio-analytics.js-integration/lib/events.js","segmentio-analytics.js-integrations/deps/integration/lib/events.js");require.alias("segmentio-analytics.js-integration/lib/statics.js","segmentio-analytics.js-integrations/deps/integration/lib/statics.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integrations/deps/integration/index.js");require.alias("avetisk-defaults/index.js","segmentio-analytics.js-integration/deps/defaults/index.js");require.alias("component-clone/index.js","segmentio-analytics.js-integration/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-emitter/index.js","segmentio-analytics.js-integration/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("ianstormtaylor-bind/index.js","segmentio-analytics.js-integration/deps/bind/index.js");require.alias("component-bind/index.js","ianstormtaylor-bind/deps/bind/index.js");require.alias("segmentio-bind-all/index.js","ianstormtaylor-bind/deps/bind-all/index.js");require.alias("component-bind/index.js","segmentio-bind-all/deps/bind/index.js");require.alias("component-type/index.js","segmentio-bind-all/deps/type/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-analytics.js-integration/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("ianstormtaylor-to-no-case/index.js","segmentio-analytics.js-integration/deps/to-no-case/index.js");require.alias("component-type/index.js","segmentio-analytics.js-integration/deps/type/index.js");require.alias("segmentio-after/index.js","segmentio-analytics.js-integration/deps/after/index.js");require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integration/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integration/deps/slug/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integration/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integration/deps/debug/debug.js");require.alias("segmentio-analytics.js-integration/lib/index.js","segmentio-analytics.js-integration/index.js");require.alias("segmentio-canonical/index.js","segmentio-analytics.js-integrations/deps/canonical/index.js");require.alias("segmentio-convert-dates/index.js","segmentio-analytics.js-integrations/deps/convert-dates/index.js");require.alias("component-clone/index.js","segmentio-convert-dates/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-convert-dates/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-extend/index.js","segmentio-analytics.js-integrations/deps/extend/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-analytics.js-integrations/deps/facade/lib/index.js");require.alias("segmentio-facade/lib/alias.js","segmentio-analytics.js-integrations/deps/facade/lib/alias.js");require.alias("segmentio-facade/lib/facade.js","segmentio-analytics.js-integrations/deps/facade/lib/facade.js");require.alias("segmentio-facade/lib/group.js","segmentio-analytics.js-integrations/deps/facade/lib/group.js");require.alias("segmentio-facade/lib/page.js","segmentio-analytics.js-integrations/deps/facade/lib/page.js");require.alias("segmentio-facade/lib/identify.js","segmentio-analytics.js-integrations/deps/facade/lib/identify.js");require.alias("segmentio-facade/lib/is-enabled.js","segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js");require.alias("segmentio-facade/lib/track.js","segmentio-analytics.js-integrations/deps/facade/lib/track.js");require.alias("segmentio-facade/lib/screen.js","segmentio-analytics.js-integrations/deps/facade/lib/screen.js");require.alias("segmentio-facade/lib/index.js","segmentio-analytics.js-integrations/deps/facade/index.js");require.alias("camshaft-require-component/index.js","segmentio-facade/deps/require-component/index.js");require.alias("segmentio-isodate-traverse/index.js","segmentio-facade/deps/isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("component-clone/index.js","segmentio-facade/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-inherit/index.js","segmentio-facade/deps/inherit/index.js");require.alias("component-trim/index.js","segmentio-facade/deps/trim/index.js");require.alias("segmentio-is-email/index.js","segmentio-facade/deps/is-email/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","segmentio-facade/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","segmentio-facade/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/lib/index.js");require.alias("ianstormtaylor-case/lib/cases.js","segmentio-obj-case/deps/case/lib/cases.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/index.js");require.alias("ianstormtaylor-to-camel-case/index.js","ianstormtaylor-case/deps/to-camel-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-camel-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-constant-case/index.js","ianstormtaylor-case/deps/to-constant-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-dot-case/index.js","ianstormtaylor-case/deps/to-dot-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-dot-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-pascal-case/index.js","ianstormtaylor-case/deps/to-pascal-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-sentence-case/index.js","ianstormtaylor-case/deps/to-sentence-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-slug-case/index.js","ianstormtaylor-case/deps/to-slug-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-slug-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-title-case/index.js","ianstormtaylor-case/deps/to-title-case/index.js");require.alias("component-escape-regexp/index.js","ianstormtaylor-to-title-case/deps/escape-regexp/index.js");require.alias("ianstormtaylor-map/index.js","ianstormtaylor-to-title-case/deps/map/index.js");require.alias("component-each/index.js","ianstormtaylor-map/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-title-case-minors/index.js","ianstormtaylor-to-title-case/deps/title-case-minors/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-to-title-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","ianstormtaylor-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-obj-case/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-facade/index.js");require.alias("segmentio-global-queue/index.js","segmentio-analytics.js-integrations/deps/global-queue/index.js");require.alias("segmentio-is-email/index.js","segmentio-analytics.js-integrations/deps/is-email/index.js");require.alias("segmentio-load-date/index.js","segmentio-analytics.js-integrations/deps/load-date/index.js");require.alias("segmentio-load-script/index.js","segmentio-analytics.js-integrations/deps/load-script/index.js");require.alias("component-type/index.js","segmentio-load-script/deps/type/index.js");require.alias("segmentio-script-onload/index.js","segmentio-analytics.js-integrations/deps/script-onload/index.js");require.alias("segmentio-script-onload/index.js","segmentio-analytics.js-integrations/deps/script-onload/index.js");require.alias("segmentio-script-onload/index.js","segmentio-script-onload/index.js");require.alias("segmentio-on-body/index.js","segmentio-analytics.js-integrations/deps/on-body/index.js");require.alias("component-each/index.js","segmentio-on-body/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("segmentio-on-error/index.js","segmentio-analytics.js-integrations/deps/on-error/index.js");require.alias("segmentio-to-iso-string/index.js","segmentio-analytics.js-integrations/deps/to-iso-string/index.js");require.alias("segmentio-to-unix-timestamp/index.js","segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js");require.alias("segmentio-use-https/index.js","segmentio-analytics.js-integrations/deps/use-https/index.js");require.alias("segmentio-when/index.js","segmentio-analytics.js-integrations/deps/when/index.js");require.alias("ianstormtaylor-callback/index.js","segmentio-when/deps/callback/index.js");require.alias("timoxley-next-tick/index.js","ianstormtaylor-callback/deps/next-tick/index.js");require.alias("timoxley-next-tick/index.js","segmentio-analytics.js-integrations/deps/next-tick/index.js");require.alias("yields-slug/index.js","segmentio-analytics.js-integrations/deps/slug/index.js");require.alias("visionmedia-batch/index.js","segmentio-analytics.js-integrations/deps/batch/index.js");require.alias("component-emitter/index.js","visionmedia-batch/deps/emitter/index.js");require.alias("component-indexof/index.js","component-emitter/deps/indexof/index.js");require.alias("visionmedia-debug/index.js","segmentio-analytics.js-integrations/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","segmentio-analytics.js-integrations/deps/debug/debug.js");require.alias("segmentio-load-pixel/index.js","segmentio-analytics.js-integrations/deps/load-pixel/index.js");require.alias("segmentio-load-pixel/index.js","segmentio-analytics.js-integrations/deps/load-pixel/index.js");require.alias("component-querystring/index.js","segmentio-load-pixel/deps/querystring/index.js");require.alias("component-trim/index.js","component-querystring/deps/trim/index.js");require.alias("component-type/index.js","component-querystring/deps/type/index.js");require.alias("segmentio-substitute/index.js","segmentio-load-pixel/deps/substitute/index.js");require.alias("segmentio-substitute/index.js","segmentio-load-pixel/deps/substitute/index.js");require.alias("segmentio-substitute/index.js","segmentio-substitute/index.js");require.alias("segmentio-load-pixel/index.js","segmentio-load-pixel/index.js");require.alias("segmentio-replace-document-write/index.js","segmentio-analytics.js-integrations/deps/replace-document-write/index.js");require.alias("segmentio-replace-document-write/index.js","segmentio-analytics.js-integrations/deps/replace-document-write/index.js");require.alias("component-domify/index.js","segmentio-replace-document-write/deps/domify/index.js");require.alias("segmentio-replace-document-write/index.js","segmentio-replace-document-write/index.js");require.alias("component-indexof/index.js","segmentio-analytics.js-integrations/deps/indexof/index.js");require.alias("component-object/index.js","segmentio-analytics.js-integrations/deps/object/index.js");require.alias("segmentio-obj-case/index.js","segmentio-analytics.js-integrations/deps/obj-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-analytics.js-integrations/deps/obj-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/lib/index.js");require.alias("ianstormtaylor-case/lib/cases.js","segmentio-obj-case/deps/case/lib/cases.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/index.js");require.alias("ianstormtaylor-to-camel-case/index.js","ianstormtaylor-case/deps/to-camel-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-camel-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-constant-case/index.js","ianstormtaylor-case/deps/to-constant-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-dot-case/index.js","ianstormtaylor-case/deps/to-dot-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-dot-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-pascal-case/index.js","ianstormtaylor-case/deps/to-pascal-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-sentence-case/index.js","ianstormtaylor-case/deps/to-sentence-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-slug-case/index.js","ianstormtaylor-case/deps/to-slug-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-slug-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-title-case/index.js","ianstormtaylor-case/deps/to-title-case/index.js");require.alias("component-escape-regexp/index.js","ianstormtaylor-to-title-case/deps/escape-regexp/index.js");require.alias("ianstormtaylor-map/index.js","ianstormtaylor-to-title-case/deps/map/index.js");require.alias("component-each/index.js","ianstormtaylor-map/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-title-case-minors/index.js","ianstormtaylor-to-title-case/deps/title-case-minors/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-to-title-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","ianstormtaylor-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-obj-case/index.js");require.alias("segmentio-canonical/index.js","analytics/deps/canonical/index.js");require.alias("segmentio-canonical/index.js","canonical/index.js");require.alias("segmentio-extend/index.js","analytics/deps/extend/index.js");require.alias("segmentio-extend/index.js","extend/index.js");require.alias("segmentio-facade/lib/index.js","analytics/deps/facade/lib/index.js");require.alias("segmentio-facade/lib/alias.js","analytics/deps/facade/lib/alias.js");require.alias("segmentio-facade/lib/facade.js","analytics/deps/facade/lib/facade.js");require.alias("segmentio-facade/lib/group.js","analytics/deps/facade/lib/group.js");require.alias("segmentio-facade/lib/page.js","analytics/deps/facade/lib/page.js");require.alias("segmentio-facade/lib/identify.js","analytics/deps/facade/lib/identify.js");require.alias("segmentio-facade/lib/is-enabled.js","analytics/deps/facade/lib/is-enabled.js");require.alias("segmentio-facade/lib/track.js","analytics/deps/facade/lib/track.js");require.alias("segmentio-facade/lib/screen.js","analytics/deps/facade/lib/screen.js");require.alias("segmentio-facade/lib/index.js","analytics/deps/facade/index.js");require.alias("segmentio-facade/lib/index.js","facade/index.js");require.alias("camshaft-require-component/index.js","segmentio-facade/deps/require-component/index.js");require.alias("segmentio-isodate-traverse/index.js","segmentio-facade/deps/isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("component-clone/index.js","segmentio-facade/deps/clone/index.js");require.alias("component-type/index.js","component-clone/deps/type/index.js");require.alias("component-inherit/index.js","segmentio-facade/deps/inherit/index.js");require.alias("component-trim/index.js","segmentio-facade/deps/trim/index.js");require.alias("segmentio-is-email/index.js","segmentio-facade/deps/is-email/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","segmentio-facade/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","segmentio-facade/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","segmentio-facade/deps/new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-facade/deps/obj-case/index.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/lib/index.js");require.alias("ianstormtaylor-case/lib/cases.js","segmentio-obj-case/deps/case/lib/cases.js");require.alias("ianstormtaylor-case/lib/index.js","segmentio-obj-case/deps/case/index.js");require.alias("ianstormtaylor-to-camel-case/index.js","ianstormtaylor-case/deps/to-camel-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-camel-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-constant-case/index.js","ianstormtaylor-case/deps/to-constant-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-dot-case/index.js","ianstormtaylor-case/deps/to-dot-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-dot-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-pascal-case/index.js","ianstormtaylor-case/deps/to-pascal-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-sentence-case/index.js","ianstormtaylor-case/deps/to-sentence-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-slug-case/index.js","ianstormtaylor-case/deps/to-slug-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-slug-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-snake-case/index.js","ianstormtaylor-case/deps/to-snake-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-to-snake-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-space-case/index.js","ianstormtaylor-case/deps/to-space-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-space-case/deps/to-no-case/index.js");require.alias("ianstormtaylor-to-title-case/index.js","ianstormtaylor-case/deps/to-title-case/index.js");require.alias("component-escape-regexp/index.js","ianstormtaylor-to-title-case/deps/escape-regexp/index.js");require.alias("ianstormtaylor-map/index.js","ianstormtaylor-to-title-case/deps/map/index.js");require.alias("component-each/index.js","ianstormtaylor-map/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-title-case-minors/index.js","ianstormtaylor-to-title-case/deps/title-case-minors/index.js");require.alias("ianstormtaylor-to-capital-case/index.js","ianstormtaylor-to-title-case/deps/to-capital-case/index.js");require.alias("ianstormtaylor-to-no-case/index.js","ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js","ianstormtaylor-case/index.js");require.alias("segmentio-obj-case/index.js","segmentio-obj-case/index.js");require.alias("segmentio-facade/lib/index.js","segmentio-facade/index.js");require.alias("segmentio-is-email/index.js","analytics/deps/is-email/index.js");require.alias("segmentio-is-email/index.js","is-email/index.js");require.alias("segmentio-is-meta/index.js","analytics/deps/is-meta/index.js");require.alias("segmentio-is-meta/index.js","is-meta/index.js");require.alias("segmentio-isodate-traverse/index.js","analytics/deps/isodate-traverse/index.js");require.alias("segmentio-isodate-traverse/index.js","isodate-traverse/index.js");require.alias("component-each/index.js","segmentio-isodate-traverse/deps/each/index.js");require.alias("component-type/index.js","component-each/deps/type/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-isodate-traverse/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-isodate-traverse/deps/isodate/index.js");require.alias("segmentio-json/index.js","analytics/deps/json/index.js");require.alias("segmentio-json/index.js","json/index.js");require.alias("component-json-fallback/index.js","segmentio-json/deps/json-fallback/index.js");require.alias("segmentio-new-date/lib/index.js","analytics/deps/new-date/lib/index.js");require.alias("segmentio-new-date/lib/milliseconds.js","analytics/deps/new-date/lib/milliseconds.js");require.alias("segmentio-new-date/lib/seconds.js","analytics/deps/new-date/lib/seconds.js");require.alias("segmentio-new-date/lib/index.js","analytics/deps/new-date/index.js");require.alias("segmentio-new-date/lib/index.js","new-date/index.js");require.alias("ianstormtaylor-is/index.js","segmentio-new-date/deps/is/index.js");require.alias("component-type/index.js","ianstormtaylor-is/deps/type/index.js");require.alias("ianstormtaylor-is-empty/index.js","ianstormtaylor-is/deps/is-empty/index.js");require.alias("segmentio-isodate/index.js","segmentio-new-date/deps/isodate/index.js");require.alias("segmentio-new-date/lib/index.js","segmentio-new-date/index.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/store.js");require.alias("segmentio-store.js/store.js","analytics/deps/store/index.js");require.alias("segmentio-store.js/store.js","store/index.js");require.alias("segmentio-store.js/store.js","segmentio-store.js/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","analytics/deps/top-domain/index.js");require.alias("segmentio-top-domain/index.js","top-domain/index.js");require.alias("component-url/index.js","segmentio-top-domain/deps/url/index.js");require.alias("segmentio-top-domain/index.js","segmentio-top-domain/index.js");require.alias("visionmedia-debug/index.js","analytics/deps/debug/index.js");require.alias("visionmedia-debug/debug.js","analytics/deps/debug/debug.js");require.alias("visionmedia-debug/index.js","debug/index.js");require.alias("yields-prevent/index.js","analytics/deps/prevent/index.js");require.alias("yields-prevent/index.js","prevent/index.js");require.alias("analytics/lib/index.js","analytics/index.js");if(typeof exports=="object"){module.exports=require("analytics")}else if(typeof define=="function"&&define.amd){define([],function(){return require("analytics")})}else{this["analytics"]=require("analytics")}})(); |
examples/real-world/src/root/routes.js | ioof-holdings/redux-dynamic-reducer | import React from 'react'
import { Route } from 'react-router'
import Loadable from 'react-loadable'
const Loading = () => <p>Loading...</p>
const loadRoute = (getPromise) => {
const RouteComponent = Loadable({
loader: () => getPromise(),
loading: Loading,
render(loaded, props) {
const Component = loaded.default;
return <Component {...props} />;
}
})
const LoadableRoute = (routeProps) => <RouteComponent {...routeProps} />
return LoadableRoute
}
export default (
<Route path="/" component={loadRoute(() => import('../app'))}>
<Route path="/:login/:name" component={loadRoute(() =>import('../repoPage'))} />
<Route path="/:login" component={loadRoute(() => import('../userPage'))} />
</Route>
)
|
lib/cli/generators/METEOR/template/.stories/index.js | nfl/react-storybook | /* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links';
import Button from './Button';
import Welcome from './Welcome';
storiesOf('Welcome', module)
.add('to Storybook', () => (
<Welcome showApp={linkTo('Button')}/>
));
storiesOf('Button', module)
.add('with text', () => (
<Button onClick={action('clicked')}>Hello Button</Button>
))
.add('with some emoji', () => (
<Button onClick={action('clicked')}>😀 😎 👍 💯</Button>
));
|
app/components/AdHocModal.js | tidepool-org/chrome-uploader | /*
* == BSD2 LICENSE ==
* Copyright (c) 2014-2016, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { sync as syncActions } from '../actions/';
import styles from '../../styles/components/AdHocModal.module.less';
import step1_img from '../../images/adhoc_s1.png';
import step2_img from '../../images/adhoc_s2.png';
const remote = require('@electron/remote');
const i18n = remote.getGlobal( 'i18n' );
export class AdHocModal extends Component {
handleContinue = () => {
const { showingAdHocPairingDialog, sync } = this.props;
showingAdHocPairingDialog.callback('adHocModalClose');
sync.dismissedAdHocPairingDialog();
};
render() {
const { showingAdHocPairingDialog } = this.props;
if(!showingAdHocPairingDialog){
return null;
}
return (
<div className={styles.modalWrap}>
<div className={styles.modal}>
<div className={styles.title}>
<div>{i18n.t('Allow the connection on the pump:')}</div>
</div>
<hr className={styles.hr} />
<div className={styles.text}>
<div className={styles.body}>
<div className={styles.step}>
<div><span className={styles.numeral}>1.</span> {i18n.t('Scroll down')}</div>
<div><img className={styles.image} src={step1_img} /></div>
</div>
<div className={styles.step}>
<div><span className={styles.numeral}>2.</span> {i18n.t('Select \"Yes\"')}</div>
<div><img className={styles.image} src={step2_img} /></div>
</div>
</div>
</div>
<hr className={styles.hr} />
<div className={styles.actions}>
<button className={styles.buttonSecondary} onClick={this.handleContinue}>
{i18n.t('Continue')}
</button>
</div>
</div>
</div>
);
}
};
export default connect(
(state, ownProps) => {
return {
showingAdHocPairingDialog: state.showingAdHocPairingDialog
};
},
(dispatch) => {
return {
sync: bindActionCreators(syncActions, dispatch)
};
}
)(AdHocModal);
|
src/client-scripts/admin-client.js | thegazelle-ad/gazelle-front-end | /* eslint-disable react/jsx-filename-extension */
// Emil hacking because he can't find a babel plugin that does it for some reason
if (!Array.prototype.flatten) {
// eslint-disable-next-line
Array.prototype.flatten = function flatten() {
return this.reduce((acc, cur) => acc.concat(cur), []);
};
}
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import falcor from 'falcor';
import routes from 'routes/admin-routes';
import { injectModelCreateElement } from 'lib/falcor/falcor-utilities';
import { ModalProvider } from 'components/admin/hocs/modals/ModalProvider';
import HttpDataSource from 'falcor-http-datasource';
import { MuiThemeProvider } from 'material-ui';
import { Provider as FalcorProvider } from 'react-falcor';
/** We need to initialize the logger */
import { initializeLogger } from 'lib/logger';
// We start with window.alert as our alert function but later will replace
// it with our alert function from ModalProvider
initializeLogger(true, window.alert);
const clientModel = new falcor.Model({
source: new HttpDataSource('/model.json'),
});
ReactDOM.render(
<MuiThemeProvider>
<FalcorProvider falcor={clientModel}>
<ModalProvider>
<Router
history={browserHistory}
routes={routes}
createElement={injectModelCreateElement(clientModel)}
/>
</ModalProvider>
</FalcorProvider>
</MuiThemeProvider>,
document.getElementById('main'),
);
|
packages/react/src/components/atoms/buttons/ButtonToggle/ButtonToggle.stories.js | massgov/mayflower | import React from 'react';
import { StoryPage } from 'StorybookConfig/preview';
import { action } from '@storybook/addon-actions';
import ButtonToggle from './index';
import ButtonToggleDocs from './ButtonToggle.md';
import buttonToggleOptions from './ButtonToggle.knobs.options';
export default {
title: 'atoms/buttons/ButtonToggle',
component: ButtonToggle,
parameters: {
docs: {
page: () => <StoryPage Description={ButtonToggleDocs} />
}
}
};
export const ButtonToggleExample = (args) => <ButtonToggle {...args} />;
ButtonToggleExample.storyName = 'Default';
ButtonToggleExample.args = {
option1: buttonToggleOptions.options[0],
option2: buttonToggleOptions.options[1],
id: 'sort',
labelText: 'Sort by:',
onChangeCallback: action('buttonToggle on select'),
defaultValue: buttonToggleOptions.options[1].value
};
ButtonToggleExample.argTypes = {
defaultValue: {
control: {
type: 'select',
options: {
[buttonToggleOptions.options[0].value]: buttonToggleOptions.options[0].value,
[buttonToggleOptions.options[1].value]: buttonToggleOptions.options[1].value
}
}
}
};
|
src/app.js | PetrBuslyuk/_______________ | import React from 'react';
import ReactDOM from 'react-dom';
import './css/main.css';
import { Header, Footer, Content } from './components';
ReactDOM.render(
<div className="main">
<Header />
<Content />
<Footer />
</div>,
document.getElementById('root')
); |
maodou/posts/client/components/admin/postsAdd.js | wuyang910217/meteor-react-redux-base | import React from 'react';
import Helmet from 'react-helmet';
export default (props) => {
return (
<div className="admin-package-wrapper row">
<Helmet
title='添加新文章'
/>
<div className="col-sm-12">
<h1 style={{marginBottom: '20px'}}>添加新文章</h1>
<form onSubmit={(e) => props.dispatch(props.addPost(e, props.coverUrl))}>
<div className="form-group">
<label htmlFor="select-category">选择分类</label>
<select id="select-category" className="form-control" name="category">
{
props.categories.length > 0 ?
props.categories.map((category, index) =>
<option key={index} value={category}>{category}</option>
) :
<option>Loading...</option>
}
</select>
</div>
<div id="upload-container">
<a className="btn btn-success" id="pickfiles" href="#">上传封面(选填)</a>
</div>
<div className="post-coverImg">
{ props.state.beginUpload ? <p>正在上传,请稍候...</p> : <span /> }
{ props.state.fileUploaded ? <p>图片上传完成.</p> : <span /> }
{ props.coverUrl ?
<img src={`${props.coverUrl}?imageView2/2/w/600/h/300/interlace/0/q/100`} alt="post cover" /> : <span />
}
</div>
<input className="form-control" type="text" placeholder="添加文章标题" name="title" />
<br />
<input className="form-control" type="text" placeholder="文章作者或者文章来源" name="author" />
<br />
<div id="editor" />
<button className="btn btn-success" type="submit">发布</button>
</form>
</div>
</div>
);
}
|
githubApp/js/pages/WelcomPage.js | anchoretics/ztf-work-app | /**
* Created by lingfengliang on 2017/3/15.
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
import HomePage from './HomePage';
export default class WelcomPage extends Component{
constructor(props){
super(props);
this.state = {
}
this.timer = setTimeout(()=>{
this.props.navigator.resetTo({component: HomePage});
},100);
}
render(){
return <View style={styles.container}>
<Text>欢迎</Text>
</View>
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
}); |
src/App.js | knod/cliff-effects-1 | import React, { Component } from 'react';
import {
HashRouter,
Route,
Switch,
} from 'react-router-dom';
import { Helmet } from 'react-helmet';
import localforage from 'localforage';
import { Confirmer } from './utils/getUserConfirmation';
// CUSTOM COMPONENTS
import { HomePage } from './containers/HomePage';
import { AboutPage } from './containers/AboutPage';
import { VisitPage } from './containers/VisitPage';
import { Footer } from './components/Footer';
import { Header } from './components/Header';
// Development HUD
import { DevSwitch } from './containers/DevSwitch';
import { DevHud } from './components/dev/DevHud';
import {
printSummaryToConsole,
addClientGetterProperty,
addEnableDevProperty,
} from './dev/command-line-utils';
// Object Manipulation
import cloneDeep from 'lodash/cloneDeep';
import merge from 'lodash/merge';
import { CLIENT_DEFAULTS } from './utils/CLIENT_DEFAULTS';
// LOCALIZATION
import { getTextForLanguage } from './utils/getTextForLanguage';
const DEV_PROPS_STORAGE_KEY = `cliffEffectsDevProps`,
LOADED_CLIENT_STORAGE_KEY = `cliffEffects_loadedClient`,
CLIENT_LAST_LOADED_STORAGE_KEY = `cliffEffects_clientLastLoaded`,
// Time-to-live for stored client data, in milliseconds
STORED_CLIENT_TTL = 1000 * 60 * 60 * 24; // 1 day
/**
* Main top-level component of the app. Contains the router that controls access
* to the {@link HomePage}, {@link VisitPage}, and {@link AboutPage}, as well
* as providing the common {@link Header} and {@link Footer} to these pages.
* It also manages the {@link DevHud}, which provides debugging and analysis
* options for developers.
*
* You can change the HashRouter tags (below if you are viewing this comment in
* the source code) to Router tags to turn off hash routing. Hash routing is
* only used to be compatible with GitHub Pages.
*
* Sends in the initial client values from {@link CLIENT_DEFAULTS} to
* {@link VisitPage}.
*
* @extends React.Component
*/
class App extends Component {
constructor (props) {
super(props);
let defaults = cloneDeep(CLIENT_DEFAULTS);
/**
* React state.
* @property {string} langCode - [ISO 639-1 code]{@link https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes} of currently selected language
* @property {object} translations - text translations in the current language (output of {@link getTextForLanguage})
* @property {object} clients - sets of client data to keep track of:
* @property {object} clients.default - default set, never changes
* @property {object} clients.loaded - set that has been loaded using the dev HUD
* @property {object} devProps - dev HUD settings. They get added as classes to the div that encloses the whole app. May want to rethink.
* @property {boolean} devProps.dev - whether dev HUD is turned on
* @property {boolean} devProps.english - whether to highlight English translations
* @property {boolean} devProps.nonEnglish - whether to highlight translations in the current language, if that language is not English
* @property {boolean} distrustConfirmed - displays modal to accept terms before allowing user to fill out form
*/
this.state = {
langCode: `en`,
translations: getTextForLanguage(`en`),
clients: {
default: defaults,
loaded: defaults,
},
// All these should be bools. For now, at least.
// They get added as classes. May want to rethink.
devProps: {
dev: false,
devHidden: false,
english: true,
nonEnglish: true,
warningOff: true,
},
distrustConfirmed: false,
};
}; // Ends constructor()
componentDidMount() {
// Webpack should remove this whole conditional when not built for development environment
if (process.env.NODE_ENV === `development`) {
Promise.all([
localforage.getItem(DEV_PROPS_STORAGE_KEY),
localforage.getItem(CLIENT_LAST_LOADED_STORAGE_KEY),
localforage.getItem(LOADED_CLIENT_STORAGE_KEY),
]).then(([
localDev,
clientLastLoaded,
loadedClient,
]) => {
if (localDev) {
this.setState((prevState) => {
const now = Date.now();
clientLastLoaded = clientLastLoaded || 0;
let state = merge({}, prevState, { devProps: localDev });
// This will clear out a loaded client from local storage
// if it's been there too long--this is for security purposes,
// as the loaded client could potentially have sensitive client
// data and we want to minimize exposure of that info.
if (now - clientLastLoaded >= STORED_CLIENT_TTL) {
localforage.removeItem(LOADED_CLIENT_STORAGE_KEY);
localforage.removeItem(CLIENT_LAST_LOADED_STORAGE_KEY);
} else {
state.clients.loaded = loadedClient;
}
return state;
}); // ends setState
} // ends if localDev
}); // ends Promise
printSummaryToConsole();
addEnableDevProperty(() => {
return this.setDev(`dev`, true);
});
addClientGetterProperty(() => {
return this.state.clients.loaded;
});
} // ends if in development environment
}; // Ends componentDidMount()
/**
* Set the human language of the app (i.e. the language in which the UI will
* display text for users to read, NOT the coding language).
* @method
* @param {object} evnt - The event object from an input that uses this event handler (not used)
* @param {object} inputProps - An object representing the properties of the Semantic UI React input component which triggered the language change.
* @param {string} inputProps.value - the [ISO 639-1 code]{@link https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes} for the newly selected language.
*/
setLanguage = (evnt, inputProps) => {
let translations = getTextForLanguage(inputProps.value);
this.setState({ language: inputProps.value, translations: translations });
};
/** Set the value of a specified key in the app state's devProps.
* These keys should only be set to boolean values (@todo enforce only allowing boolean values?).
* Keys with a value of true are added as classes to the app's main element when it is rendered.
* @method
* @param {string} key - The key whose value is to be changed in the app state's devProps
* @param {boolean} value - The value to be set for the given key in the app state's devProps
*/
setDev = (key, value) => {
this.setState((prevState) => {
let props = prevState.devProps;
if (props[ key ] !== value) {
let newProps = { ...props, [ key ]: value };
if (process.env.NODE_ENV === `development`) {
localforage.setItem(DEV_PROPS_STORAGE_KEY, newProps);
}
return { devProps: newProps };
}
});
};
/** Load an individual client's data. Currently, the only source of client
* data to load is a text input field in the Dev HUD.
* @method
* @param {object} params
* @param {object} params.toLoad - A JSON object representing the client data
* to be loaded. Must match the client data format (See
* {@link CLIENT_DEFAULTS} for an example of the correct client data format)
*/
loadClient = ({ toLoad }) => {
this.setState((prevState) => {
const clients = cloneDeep(prevState.clients),
defaults = cloneDeep(clients.default),
newData = Object.assign(defaults, toLoad);
if (process.env.NODE_ENV === `development`) {
localforage.setItem(CLIENT_LAST_LOADED_STORAGE_KEY, Date.now());
localforage.setItem(LOADED_CLIENT_STORAGE_KEY, newData);
}
return { clients: { ...clients, loaded: newData }};
});
};
/** Concatenate the true boolean values in input object to a space-delimited
* string, for use as a CSS class string. Currently used to convert
* [devProps]{@link App#state} to classes for the rendered `div`.
* @method
* @param {object} obj - the object to be converted to a string
* @returns {string} a string constructed by concatenating together the keys
* of obj with values equal to true, separated by spaces.
*/
propsToClasses (obj) {
let classes = ``;
for (let key in obj) {
if (obj[ key ] === true) {
classes += ` ` + key;
}
}
return classes;
};
/** Toggles distrustConfirmed flag in app state. Passed to PredictionsWarning modal
* which calls this in the onClose handler. App is unavailable until terms
* are accepted unless warningOff is set to true in DevHud.
* @method
*/
toggleDistrustConfirmed = () => {
let userDistrusts = this.state.distrustConfirmed;
this.setState({ distrustConfirmed: !userDistrusts });
};
// @todo I think we can remove langCode from translations now
render () {
let {
langCode,
translations,
devProps,
clients,
distrustConfirmed,
} = this.state;
let { warningOff } = devProps;
let confirmer = new Confirmer(), // Makes sure user doesn't accidentally lose work
classes = this.propsToClasses(devProps),
devFuncs = {
setDev: this.setDev,
loadClient: this.loadClient,
setLanguage: this.setLanguage,
},
funcs = { toggleDistrustConfirmed: this.toggleDistrustConfirmed },
clientData = clients.loaded;
return (
<div
id = { `App` }
className = { classes }>
<Helmet>
<html lang={ langCode } />
</Helmet>
<HashRouter getUserConfirmation={ confirmer.getConfirmation }>
<div id={ `HashRouter` }>
<Route
path = { `/:rest+` }
component = { (props) => { return (
<Header
{ ...props }
translations = {{ ...translations.header, langCode: translations.langCode }} />
);} } />
<Switch>
<Route
exact
path = { `/` }
component = { (props) => { return (
<HomePage
{ ...props }
translations = {{ ...translations.homePage, langCode: translations.langCode }} />
);} } />
<Route
path = { `/about` }
component = { (props) => { return (
<AboutPage
{ ...props }
translations = {{ ...translations.aboutPage, langCode: translations.langCode }} />
);} } />
<Route
path = { `/visit/:clientId/:visitId/:stepKey?` }
component = { ({ match, history, ...props }) => {
const { clientId, visitId, stepKey } = match.params;
return (
<VisitPage
{ ...props }
history = { history }
clientId = { clientId }
visitId = { visitId }
stepKey = { stepKey }
distrustConfirmed = { distrustConfirmed || warningOff }
funcs = { funcs }
confirmer = { confirmer }
translations = {{ ...translations.visitPage, langCode: translations.langCode }}
clientData = { clientData } />
);
} } />
{/* For managing our development HUD */}
<Route
path = { `/dev` }
component = { (props) => { return (
<DevSwitch
{ ...props }
setDev = { this.setDev }
devProps = { devProps } />
);} } />
</Switch>
</div>
</HashRouter>
<Footer translations={{ ...translations.footer, langCode: translations.langCode }} />
{ (devProps.dev === true) ? (
<DevHud
devProps = { devProps }
funcs = { devFuncs }
data = {{ default: clients.default }}
state = { this.state } />
) : (
null
) }
</div>
);
}; // Ends render()
}; // Ends <App>
export { App };
|
src/routes.js | jmattfong/jmattfong.com | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import Router from 'react-routing/src/Router';
import http from './core/HttpClient';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import LoginPage from './components/LoginPage';
import RegisterPage from './components/RegisterPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
const router = new Router(on => {
on('*', async (state, next) => {
const component = await next();
return component && <App context={state.context}>{component}</App>;
});
on('/contact', async () => <ContactPage />);
on('/login', async () => <LoginPage />);
on('/register', async () => <RegisterPage />);
on('*', async (state) => {
const content = await http.get(`/api/content?path=${state.path}`);
return content && <ContentPage {...content} />;
});
on('error', (state, error) => state.statusCode === 404 ?
<App context={state.context} error={error}><NotFoundPage /></App> :
<App context={state.context} error={error}><ErrorPage /></App>
);
});
export default router;
|
jekyll-strapi-tutorial/api/plugins/content-type-builder/admin/src/components/EmptyContentTypeView/index.js | strapi/strapi-examples | /**
*
* EmptyContentTypeView
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Button from 'components/Button';
import Brush from '../../assets/images/paint_brush.svg';
import styles from './styles.scss';
class EmptyContentTypeView extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div className={styles.emptyContentTypeView}>
<img src={Brush} alt="" />
<div>
<FormattedMessage id="content-type-builder.home.emptyContentType.title">
{(title) => <div className={styles.title}>{title}</div>}
</FormattedMessage>
<FormattedMessage id="content-type-builder.home.emptyContentType.description">
{(description) => <div className={styles.description}>{description}</div>}
</FormattedMessage>
<div className={styles.buttonContainer}>
<Button
primaryAddShape
label={'content-type-builder.button.contentType.create'}
onClick={this.props.handleButtonClick}
/>
</div>
</div>
</div>
);
}
}
EmptyContentTypeView.propTypes = {
handleButtonClick: PropTypes.func.isRequired,
};
export default EmptyContentTypeView;
|
protocol-designer/src/components/StepDescription.js | Opentrons/labware | // @flow
import * as React from 'react'
import styles from './StepDescription.css'
type StepDescriptionProps = {|
description: ?string,
|}
// TODO Ian 2018-02-21 rename TitledListDescription or whatever, it's not just for StepList but also for IngredientsList
export function StepDescription(props: StepDescriptionProps): React.Node {
// TODO Ian 2017-01-12 Not really styled
return (
<div className={styles.step_description}>
<header>{'Notes:'}</header>
{props.description}
</div>
)
}
|
examples/with-why-did-you-render/scripts/wdyr.js | azukaru/next.js | import React from 'react'
if (process.env.NODE_ENV === 'development') {
if (typeof window !== 'undefined') {
const whyDidYouRender = require('@welldone-software/why-did-you-render')
whyDidYouRender(React, {
trackAllPureComponents: true,
})
}
}
|
frontend/src/components/TimeStamp/index.js | plusbeauxjours/nomadgram | import React from 'react';
import PropTypes from 'prop-types';
import styles from './styles.scss';
const TimeStamp = (
{
time
},
context
) => (
<span className={styles.time}>{time}</span>
);
TimeStamp.propTypes = {
time: PropTypes.string.isRequired
};
TimeStamp.contextTypes = {
t: PropTypes.func.isRequired
}
export default TimeStamp; |
ajax/libs/react/0.3.2/react.js | tharakauka/cdnjs | /**
* React v0.3.2
*/
(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(){var define,ses,bootstrap,module,exports;
return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
/**
* 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.
*
* @providesModule React
*/
"use strict";
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactComponent = require("./ReactComponent");
var ReactDOM = require("./ReactDOM");
var ReactMount = require("./ReactMount");
var ReactDefaultInjection = require("./ReactDefaultInjection");
ReactDefaultInjection.inject();
var React = {
DOM: ReactDOM,
initializeTouchEvents: function(shouldUseTouch) {
ReactMount.useTouchEvents = shouldUseTouch;
},
autoBind: ReactCompositeComponent.autoBind,
createClass: ReactCompositeComponent.createClass,
createComponentRenderer: ReactMount.createComponentRenderer,
constructAndRenderComponent: ReactMount.constructAndRenderComponent,
constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
renderComponent: ReactMount.renderComponent,
unmountAndReleaseReactRootNode: ReactMount.unmountAndReleaseReactRootNode,
isValidComponent: ReactComponent.isValidComponent
};
module.exports = React;
},{"./ReactCompositeComponent":2,"./ReactComponent":3,"./ReactDOM":4,"./ReactMount":5,"./ReactDefaultInjection":6}],2:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule ReactCompositeComponent
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactOwner = require("./ReactOwner");
var ReactPropTransferer = require("./ReactPropTransferer");
var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
var merge = require("./merge");
var mixInto = require("./mixInto");
/**
* Policies that describe methods in `ReactCompositeComponentInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base ReactCompositeComponent class.
*/
OVERRIDE_BASE: null
});
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactCompositeComponent`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will available on the prototype.
*
* @interface ReactCompositeComponentInterface
* @internal
*/
var ReactCompositeComponentInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* Definition of props for this component.
*
* @type {array}
* @optional
*/
props: SpecPolicy.DEFINE_ONCE,
// ==== Definition methods ====
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_ONCE,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props and state.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props and state will not require a component update.
*
* shouldComponentUpdate: function(nextProps, nextState) {
* return !equal(nextProps, this.props) || !equal(nextState, this.state);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props` and `this.state` to `nextProps` and `nextState`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared in the specification when defining classes
* using `React.createClass`, they will not be on the component's prototype.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
props: function(Constructor, props) {
Constructor.propDeclarations = props;
}
};
/**
* Custom version of `mixInto` which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
var proto = Constructor.prototype;
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
var property = spec[name];
var specPolicy = ReactCompositeComponentInterface[name];
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
invariant(
specPolicy === SpecPolicy.OVERRIDE_BASE,
'ReactCompositeComponentInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
);
}
// Disallow using `React.autoBind` on internal methods.
if (specPolicy != null) {
invariant(
!property || !property.__reactAutoBind,
'ReactCompositeComponentInterface: You are attempting to use ' +
'`React.autoBind` on `%s`, a method that is internal to React.' +
'Internal methods are called with the component as the context.',
name
);
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
invariant(
specPolicy === SpecPolicy.DEFINE_MANY,
'ReactCompositeComponentInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
);
}
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else if (property && property.__reactAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property.__reactAutoBind;
} else if (proto.hasOwnProperty(name)) {
// For methods which are defined more than once, call the existing methods
// before calling the new property.
proto[name] = createChainedFunction(proto[name], property);
} else {
proto[name] = property;
}
}
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction(a, b, c, d, e, tooMany) {
invariant(
typeof tooMany === 'undefined',
'Chained function can only take a maximum of 5 arguments.'
);
one.call(this, a, b, c, d, e);
two.call(this, a, b, c, d, e);
};
}
/**
* `ReactCompositeComponent` maintains an auxiliary life cycle state in
* `this._compositeLifeCycleState` (which can be null).
*
* This is different from the life cycle state maintained by `ReactComponent` in
* `this._lifeCycleState`.
*/
var CompositeLifeCycle = keyMirror({
/**
* Components in the process of being mounted respond to state changes
* differently.
*/
MOUNTING: null,
/**
* Components in the process of being unmounted are guarded against state
* changes.
*/
UNMOUNTING: null,
/**
* Components that are mounted and receiving new props respond to state
* changes differently.
*/
RECEIVING_PROPS: null,
/**
* Components that are mounted and receiving new state are guarded against
* additional state changes.
*/
RECEIVING_STATE: null
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {?object} initialProps
* @param {*} children
* @final
* @internal
*/
construct: function(initialProps, children) {
ReactComponent.Mixin.construct.call(this, initialProps, children);
this.state = null;
this._pendingState = null;
this._compositeLifeCycleState = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function(rootID, transaction) {
ReactComponent.Mixin.mountComponent.call(this, rootID, transaction);
// Unset `this._lifeCycleState` until after this method is finished.
this._lifeCycleState = ReactComponent.LifeCycle.UNMOUNTED;
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
if (this.constructor.propDeclarations) {
this._assertValidProps(this.props);
}
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.state = this.getInitialState ? this.getInitialState() : null;
this._pendingState = null;
if (this.componentWillMount) {
this.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingState` without triggering a re-render.
if (this._pendingState) {
this.state = this._pendingState;
this._pendingState = null;
}
}
if (this.componentDidMount) {
transaction.getReactOnDOMReady().enqueue(this, this.componentDidMount);
}
this._renderedComponent = this._renderValidatedComponent();
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
this._lifeCycleState = ReactComponent.LifeCycle.MOUNTED;
return this._renderedComponent.mountComponent(rootID, transaction);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
ReactComponent.Mixin.unmountComponent.call(this);
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
if (this.refs) {
this.refs = null;
}
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = null;
},
/**
* Updates the rendered DOM nodes given a new set of props.
*
* @param {object} nextProps Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @final
* @internal
*/
receiveProps: function(nextProps, transaction) {
if (this.constructor.propDeclarations) {
this._assertValidProps(nextProps);
}
ReactComponent.Mixin.receiveProps.call(this, nextProps, transaction);
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, transaction);
}
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE;
// When receiving props, calls to `setState` by `componentWillReceiveProps`
// will set `this._pendingState` without triggering a re-render.
var nextState = this._pendingState || this.state;
this._pendingState = null;
this._receivePropsAndState(nextProps, nextState, transaction);
this._compositeLifeCycleState = null;
},
/**
* Sets a subset of the state. Always use this or `replaceState` to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {object} partialState Next partial state to be merged with state.
* @final
* @protected
*/
setState: function(partialState) {
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(merge(this._pendingState || this.state, partialState));
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {object} completeState Next state.
* @final
* @protected
*/
replaceState: function(completeState) {
var compositeLifeCycleState = this._compositeLifeCycleState;
invariant(
this._lifeCycleState === ReactComponent.LifeCycle.MOUNTED ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted (or mounting) component.'
);
invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component or during ' +
'an existing state transition (such as within `render`).'
);
this._pendingState = completeState;
// Do not trigger a state transition if we are in the middle of mounting or
// receiving props because both of those will already be doing this.
if (compositeLifeCycleState !== CompositeLifeCycle.MOUNTING &&
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_PROPS) {
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE;
var nextState = this._pendingState;
this._pendingState = null;
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(
this._receivePropsAndState,
this,
this.props,
nextState,
transaction
);
ReactComponent.ReactReconcileTransaction.release(transaction);
this._compositeLifeCycleState = null;
}
},
/**
* Receives next props and next state, and negotiates whether or not the
* component should update as a result.
*
* @param {object} nextProps Next object to set as props.
* @param {?object} nextState Next object to set as state.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_receivePropsAndState: function(nextProps, nextState, transaction) {
if (!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState)) {
// Will set `this.props` and `this.state`.
this._performComponentUpdate(nextProps, nextState, transaction);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this.props = nextProps;
this.state = nextState;
}
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {object} nextProps Next object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_performComponentUpdate: function(nextProps, nextState, transaction) {
var prevProps = this.props;
var prevState = this.state;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, transaction);
}
this.props = nextProps;
this.state = nextState;
this.updateComponent(transaction);
if (this.componentDidUpdate) {
transaction.getReactOnDOMReady().enqueue(
this,
this.componentDidUpdate.bind(this, prevProps, prevState)
);
}
},
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: function(transaction) {
var currentComponent = this._renderedComponent;
var nextComponent = this._renderValidatedComponent();
if (currentComponent.constructor === nextComponent.constructor) {
if (!nextComponent.props.isStatic) {
currentComponent.receiveProps(nextComponent.props, transaction);
}
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var currentComponentID = currentComponent._rootNodeID;
currentComponent.unmountComponent();
var nextMarkup = nextComponent.mountComponent(thisID, transaction);
ReactComponent.DOMIDOperations.dangerouslyReplaceNodeWithMarkupByID(
currentComponentID,
nextMarkup
);
this._renderedComponent = nextComponent;
}
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @final
* @protected
*/
forceUpdate: function() {
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(
this._performComponentUpdate,
this,
this.props,
this.state,
transaction
);
ReactComponent.ReactReconcileTransaction.release(transaction);
},
/**
* @private
*/
_renderValidatedComponent: function() {
ReactCurrentOwner.current = this;
var renderedComponent = this.render();
ReactCurrentOwner.current = null;
invariant(
ReactComponent.isValidComponent(renderedComponent),
'%s.render(): A valid ReactComponent must be returned.',
this.constructor.displayName || 'ReactCompositeComponent'
);
return renderedComponent;
},
/**
* @param {object} props
* @private
*/
_assertValidProps: function(props) {
var propDeclarations = this.constructor.propDeclarations;
var componentName = this.constructor.displayName;
for (var propName in propDeclarations) {
var checkProp = propDeclarations[propName];
if (checkProp) {
checkProp(props, propName, componentName);
}
}
},
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(method);
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var hasWarned = false;
function autoBound(a, b, c, d, e, tooMany) {
invariant(
typeof tooMany === 'undefined',
'React.autoBind(...): Methods can only take a maximum of 5 arguments.'
);
if (component._lifeCycleState === ReactComponent.LifeCycle.MOUNTED) {
return method.call(component, a, b, c, d, e);
} else if (!hasWarned) {
hasWarned = true;
if (true) {
console.warn(
'React.autoBind(...): Attempted to invoke an auto-bound method ' +
'on an unmounted instance of `%s`. You either have a memory leak ' +
'or an event handler that is being run after unmounting.',
component.constructor.displayName || 'ReactCompositeComponent'
);
}
}
}
return autoBound;
}
};
var ReactCompositeComponentBase = function() {};
mixInto(ReactCompositeComponentBase, ReactComponent.Mixin);
mixInto(ReactCompositeComponentBase, ReactOwner.Mixin);
mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin);
mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin);
/**
* Module for creating composite components.
*
* @class ReactCompositeComponent
* @extends ReactComponent
* @extends ReactOwner
* @extends ReactPropTransferer
*/
var ReactCompositeComponent = {
LifeCycle: CompositeLifeCycle,
Base: ReactCompositeComponentBase,
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function(spec) {
var Constructor = function(initialProps, children) {
this.construct(initialProps, children);
};
Constructor.prototype = new ReactCompositeComponentBase();
Constructor.prototype.constructor = Constructor;
mixSpecIntoComponent(Constructor, spec);
invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
);
var ConvenienceConstructor = function(props, children) {
return new Constructor(props, children);
};
ConvenienceConstructor.componentConstructor = Constructor;
ConvenienceConstructor.originalSpec = spec;
return ConvenienceConstructor;
},
/**
* Marks the provided method to be automatically bound to the component.
* This means the method's context will always be the component.
*
* React.createClass({
* handleClick: React.autoBind(function() {
* this.setState({jumping: true});
* }),
* render: function() {
* return <a onClick={this.handleClick}>Jump</a>;
* }
* });
*
* @param {function} method Method to be bound.
* @public
*/
autoBind: function(method) {
function unbound() {
invariant(
false,
'React.autoBind(...): Attempted to invoke an auto-bound method that ' +
'was not correctly defined on the class specification.'
);
}
unbound.__reactAutoBind = method;
return unbound;
}
};
module.exports = ReactCompositeComponent;
})()
},{"./ReactComponent":3,"./ReactCurrentOwner":7,"./ReactOwner":8,"./ReactPropTransferer":9,"./invariant":10,"./keyMirror":11,"./merge":12,"./mixInto":13}],3:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactComponent
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactDOMIDOperations = require("./ReactDOMIDOperations");
var ReactMount = require("./ReactMount");
var ReactOwner = require("./ReactOwner");
var ReactReconcileTransaction = require("./ReactReconcileTransaction");
var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
var merge = require("./merge");
/**
* Prop key that references a component's owner.
* @private
*/
var OWNER = '{owner}';
/**
* Every React component is in one of these life cycles.
*/
var ComponentLifeCycle = keyMirror({
/**
* Mounted components have a DOM node representation and are capable of
* receiving new props.
*/
MOUNTED: null,
/**
* Unmounted components are inactive and cannot receive new props.
*/
UNMOUNTED: null
});
/**
* Components are the basic units of composition in React.
*
* Every component accepts a set of keyed input parameters known as "props" that
* are initialized by the constructor. Once a component is mounted, the props
* can be mutated using `setProps` or `replaceProps`.
*
* Every component is capable of the following operations:
*
* `mountComponent`
* Initializes the component, renders markup, and registers event listeners.
*
* `receiveProps`
* Updates the rendered DOM nodes given a new set of props.
*
* `unmountComponent`
* Releases any resources allocated by this component.
*
* Components can also be "owned" by other components. Being owned by another
* component means being constructed by that component. This is different from
* being the child of a component, which means having a DOM representation that
* is a child of the DOM representation of that component.
*
* @class ReactComponent
*/
var ReactComponent = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
isValidComponent: function(object) {
return !!(
object &&
typeof object.mountComponentIntoNode === 'function' &&
typeof object.receiveProps === 'function'
);
},
/**
* @internal
*/
LifeCycle: ComponentLifeCycle,
/**
* React references `ReactDOMIDOperations` using this property in order to
* allow dependency injection.
*
* @internal
*/
DOMIDOperations: ReactDOMIDOperations,
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: ReactReconcileTransaction,
/**
* @param {object} DOMIDOperations
* @final
*/
setDOMOperations: function(DOMIDOperations) {
ReactComponent.DOMIDOperations = DOMIDOperations;
},
/**
* @param {Transaction} ReactReconcileTransaction
* @final
*/
setReactReconcileTransaction: function(ReactReconcileTransaction) {
ReactComponent.ReactReconcileTransaction = ReactReconcileTransaction;
},
/**
* Base functionality for every ReactComponent constructor.
*
* @lends {ReactComponent.prototype}
*/
Mixin: {
/**
* Returns the DOM node rendered by this component.
*
* @return {?DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function() {
invariant(
ExecutionEnvironment.canUseDOM,
'getDOMNode(): The DOM is not supported in the current environment.'
);
invariant(
this._lifeCycleState === ComponentLifeCycle.MOUNTED,
'getDOMNode(): A component must be mounted to have a DOM node.'
);
var rootNode = this._rootNode;
if (!rootNode) {
rootNode = document.getElementById(this._rootNodeID);
if (!rootNode) {
// TODO: Log the frequency that we reach this path.
rootNode = ReactMount.findReactRenderedDOMNodeSlow(this._rootNodeID);
}
this._rootNode = rootNode;
}
return rootNode;
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @final
* @public
*/
setProps: function(partialProps) {
this.replaceProps(merge(this.props, partialProps));
},
/**
* Replaces all of the props.
*
* @param {object} props New props.
* @final
* @public
*/
replaceProps: function(props) {
invariant(
!this.props[OWNER],
'replaceProps(...): You called `setProps` or `replaceProps` on a ' +
'component with an owner. This is an anti-pattern since props will ' +
'get reactively updated when rendered. Instead, change the owner\'s ' +
'`render` method to pass the correct value as props to the component ' +
'where it is created.'
);
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(this.receiveProps, this, props, transaction);
ReactComponent.ReactReconcileTransaction.release(transaction);
},
/**
* Base constructor for all React component.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.construct.call(this, ...)`.
*
* @param {?object} initialProps
* @param {*} children
* @internal
*/
construct: function(initialProps, children) {
this.props = initialProps || {};
if (typeof children !== 'undefined') {
this.props.children = children;
}
// Record the component responsible for creating this component.
this.props[OWNER] = ReactCurrentOwner.current;
// All components start unmounted.
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* NOTE: This does not insert any nodes into the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.mountComponent.call(this, ...)`.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @internal
*/
mountComponent: function(rootID, transaction) {
invariant(
this._lifeCycleState === ComponentLifeCycle.UNMOUNTED,
'mountComponent(%s, ...): Can only mount an unmounted component.',
rootID
);
var props = this.props;
if (props.ref != null) {
ReactOwner.addComponentAsRefTo(this, props.ref, props[OWNER]);
}
this._rootNodeID = rootID;
this._lifeCycleState = ComponentLifeCycle.MOUNTED;
// Effectively: return '';
},
/**
* Releases any resources allocated by `mountComponent`.
*
* NOTE: This does not remove any nodes from the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.unmountComponent.call(this)`.
*
* @internal
*/
unmountComponent: function() {
invariant(
this._lifeCycleState === ComponentLifeCycle.MOUNTED,
'unmountComponent(): Can only unmount a mounted component.'
);
var props = this.props;
if (props.ref != null) {
ReactOwner.removeComponentAsRefFrom(this, props.ref, props[OWNER]);
}
this._rootNode = null;
this._rootNodeID = null;
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
},
/**
* Updates the rendered DOM nodes given a new set of props.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.receiveProps.call(this, ...)`.
*
* @param {object} nextProps Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveProps: function(nextProps, transaction) {
invariant(
this._lifeCycleState === ComponentLifeCycle.MOUNTED,
'receiveProps(...): Can only update a mounted component.'
);
var props = this.props;
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`.
if (nextProps[OWNER] !== props[OWNER] || nextProps.ref !== props.ref) {
if (props.ref != null) {
ReactOwner.removeComponentAsRefFrom(this, props.ref, props[OWNER]);
}
// Correct, even if the owner is the same, and only the ref has changed.
if (nextProps.ref != null) {
ReactOwner.addComponentAsRefTo(this, nextProps.ref, nextProps[OWNER]);
}
}
},
/**
* Mounts this component and inserts it into the DOM.
*
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @final
* @internal
* @see {ReactMount.renderComponent}
*/
mountComponentIntoNode: function(rootID, container) {
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(
this._mountComponentIntoNode,
this,
rootID,
container,
transaction
);
ReactComponent.ReactReconcileTransaction.release(transaction);
},
/**
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @final
* @private
*/
_mountComponentIntoNode: function(rootID, container, transaction) {
var renderStart = Date.now();
var markup = this.mountComponent(rootID, transaction);
ReactMount.totalInstantiationTime += (Date.now() - renderStart);
var injectionStart = Date.now();
// Asynchronously inject markup by ensuring that the container is not in
// the document when settings its `innerHTML`.
var parent = container.parentNode;
if (parent) {
var next = container.nextSibling;
parent.removeChild(container);
container.innerHTML = markup;
if (next) {
parent.insertBefore(container, next);
} else {
parent.appendChild(container);
}
} else {
container.innerHTML = markup;
}
ReactMount.totalInjectionTime += (Date.now() - injectionStart);
},
/**
* Unmounts this component and removes it from the DOM.
*
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountAndReleaseReactRootNode}
*/
unmountComponentFromNode: function(container) {
this.unmountComponent();
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
},
/**
* Checks if this component is owned by the supplied `owner` component.
*
* @param {ReactComponent} owner Component to check.
* @return {boolean} True if `owners` owns this component.
* @final
* @internal
*/
isOwnedBy: function(owner) {
return this.props[OWNER] === owner;
}
}
};
function logDeprecated(msg) {
if (true) {
throw new Error(msg);
}
}
/**
* @deprecated
*/
ReactComponent.Mixin.update = function(props) {
logDeprecated('this.update() is deprecated. Use this.setProps()');
this.setProps(props);
};
ReactComponent.Mixin.updateAll = function(props) {
logDeprecated('this.updateAll() is deprecated. Use this.replaceProps()');
this.replaceProps(props);
};
module.exports = ReactComponent;
},{"./ExecutionEnvironment":14,"./ReactCurrentOwner":7,"./ReactDOMIDOperations":15,"./ReactMount":5,"./ReactOwner":8,"./ReactReconcileTransaction":16,"./invariant":10,"./keyMirror":11,"./merge":12}],4:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactDOM
* @typechecks
*/
"use strict";
var ReactNativeComponent = require("./ReactNativeComponent");
var mergeInto = require("./mergeInto");
var objMapKeyVal = require("./objMapKeyVal");
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @param {string} tag Tag name (e.g. `div`).
* @param {boolean} omitClose True if the close tag should be omitted.
* @private
*/
function createDOMComponentClass(tag, omitClose) {
var Constructor = function(initialProps, children) {
this.construct(initialProps, children);
};
Constructor.prototype = new ReactNativeComponent(tag, omitClose);
Constructor.prototype.constructor = Constructor;
return function(props, children) {
return new Constructor(props, children);
};
}
/**
* Creates a mapping from supported HTML tags to `ReactNativeComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOM = objMapKeyVal({
a: false,
abbr: false,
address: false,
audio: false,
b: false,
body: false,
br: true,
button: false,
code: false,
col: true,
colgroup: false,
dd: false,
div: false,
section: false,
dl: false,
dt: false,
em: false,
embed: true,
fieldset: false,
footer: false,
// Danger: this gets monkeypatched! See ReactDOMForm for more info.
form: false,
h1: false,
h2: false,
h3: false,
h4: false,
h5: false,
h6: false,
header: false,
hr: true,
i: false,
iframe: false,
img: true,
input: true,
label: false,
legend: false,
li: false,
line: false,
nav: false,
object: false,
ol: false,
optgroup: false,
option: false,
p: false,
param: true,
pre: false,
select: false,
small: false,
source: false,
span: false,
sub: false,
sup: false,
strong: false,
table: false,
tbody: false,
td: false,
textarea: false,
tfoot: false,
th: false,
thead: false,
time: false,
title: false,
tr: false,
u: false,
ul: false,
video: false,
wbr: false,
// SVG
circle: false,
g: false,
path: false,
polyline: false,
rect: false,
svg: false,
text: false
}, createDOMComponentClass);
var injection = {
injectComponentClasses: function(componentClasses) {
mergeInto(ReactDOM, componentClasses);
}
};
ReactDOM.injection = injection;
module.exports = ReactDOM;
},{"./ReactNativeComponent":17,"./mergeInto":18,"./objMapKeyVal":19}],5:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule ReactMount
*/
"use strict";
var ReactEvent = require("./ReactEvent");
var ReactInstanceHandles = require("./ReactInstanceHandles");
var ReactEventTopLevelCallback = require("./ReactEventTopLevelCallback");
var $ = require("./$");
var globalMountPointCounter = 0;
/** Mapping from reactRoot DOM ID to React component instance. */
var instanceByReactRootID = {};
/** Mapping from reactRoot DOM ID to `container` nodes. */
var containersByReactRootID = {};
/**
* @param {DOMElement} container DOM element that may contain a React component.
* @return {?string} A "reactRoot" ID, if a React component is rendered.
*/
function getReactRootID(container) {
return container.firstChild && container.firstChild.id;
}
/**
* Mounting is the process of initializing a React component by creatings its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.renderComponent(component, $('container'));
*
* <div id="container"> <-- Supplied `container`.
* <div id=".reactRoot[3]"> <-- Rendered reactRoot of React component.
* // ...
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
/** Time spent generating markup. */
totalInstantiationTime: 0,
/** Time spent inserting markup into the DOM. */
totalInjectionTime: 0,
/** Whether support for touch events should be initialized. */
useTouchEvents: false,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function(container, renderCallback) {
renderCallback();
},
/**
* Ensures tht the top-level event delegation listener is set up. This will be
* invoked some time before the first time any React component is rendered.
*
* @param {object} TopLevelCallbackCreator
* @private
*/
prepareTopLevelEvents: function(TopLevelCallbackCreator) {
ReactEvent.ensureListening(
ReactMount.useTouchEvents,
TopLevelCallbackCreator
);
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} nextComponent Component instance to render.
* @param {DOMElement} container DOM element to render into.
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderComponent: function(nextComponent, container) {
var prevComponent = instanceByReactRootID[getReactRootID(container)];
if (prevComponent) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps);
});
return prevComponent;
}
ReactMount.prepareTopLevelEvents(ReactEventTopLevelCallback);
var reactRootID = ReactMount.registerContainer(container);
instanceByReactRootID[reactRootID] = nextComponent;
nextComponent.mountComponentIntoNode(reactRootID, container);
return nextComponent;
},
/**
* Creates a function that accepts a `container` and renders the supplied
* React component instance into it.
*
* var renderInto = ReactMount.createComponentRenderer(component);
* // ...
* var component = renderInto($('container'));
*
* @param {ReactComponent} component Component instance to render.
* @return {function(DOMElement): ReactComponent}
*/
createComponentRenderer: function(component) {
return function(container) {
return ReactMount.renderComponent(component, container);
};
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into the supplied `container`.
*
* @param {function} constructor React component constructor.
* @param {?object} props Initial props of the component instance.
* @param {DOMElement} container DOM element to render into.
* @return {ReactComponent} Component instance rendered in `container`.
*/
constructAndRenderComponent: function(constructor, props, container) {
return ReactMount.renderComponent(constructor(props), container);
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into a container node identified by supplied `id`.
*
* @param {function} componentConstructor React component constructor
* @param {?object} props Initial props of the component instance.
* @param {string} id ID of the DOM element to render into.
* @return {ReactComponent} Component instance rendered in the container node.
*/
constructAndRenderComponentByID: function(constructor, props, id) {
return ReactMount.constructAndRenderComponent(constructor, props, $(id));
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reatRoot" ID that will be assigned to the element
* rendered within.
*
* @param {DOMElement} container DOM element to register as a container.
* @return {string} The "reactRoot" ID of elements rendered within.
*/
registerContainer: function(container) {
var reactRootID = getReactRootID(container);
if (reactRootID) {
// If one exists, make sure it is a valid "reactRoot" ID.
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
}
if (!reactRootID) {
// No valid "reactRoot" ID found, create one.
reactRootID = ReactInstanceHandles.getReactRootID(
globalMountPointCounter++
);
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
*/
unmountAndReleaseReactRootNode: function(container) {
var reactRootID = getReactRootID(container);
var component = instanceByReactRootID[reactRootID];
// TODO: Consider throwing if no `component` was found.
component.unmountComponentFromNode(container);
delete instanceByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
},
/**
* Finds the container DOM element that contains React component to which the
* supplied DOM `id` belongs.
*
* @param {string} id The ID of an element rendered by a React component.
* @return {?DOMElement} DOM element that contains the `id`.
*/
findReactContainerForID: function(id) {
var reatRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
// TODO: Consider throwing if `id` is not a valid React element ID.
return containersByReactRootID[reatRootID];
},
/**
* Given the ID of a DOM node rendered by a React component, finds the root
* DOM node of the React component.
*
* @param {string} id ID of a DOM node in the React component.
* @return {?DOMElement} Root DOM node of the React component.
*/
findReactRenderedDOMNodeSlow: function(id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactInstanceHandles.findComponentRoot(reactRoot, id);
}
};
module.exports = ReactMount;
})()
},{"./ReactEvent":20,"./ReactInstanceHandles":21,"./ReactEventTopLevelCallback":22,"./$":23}],6:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactDefaultInjection
*/
"use strict";
var ReactDOM = require("./ReactDOM");
var ReactDOMForm = require("./ReactDOMForm");
var DefaultEventPluginOrder = require("./DefaultEventPluginOrder");
var EnterLeaveEventPlugin = require("./EnterLeaveEventPlugin");
var EventPluginHub = require("./EventPluginHub");
var ReactInstanceHandles = require("./ReactInstanceHandles");
var SimpleEventPlugin = require("./SimpleEventPlugin");
function inject() {
/**
* Inject module for resolving DOM hierarchy and plugin ordering.
*/
EventPluginHub.injection.injectEventPluginOrder(DefaultEventPluginOrder);
EventPluginHub.injection.injectInstanceHandle(ReactInstanceHandles);
/**
* Two important event plugins included by default (without having to require
* them).
*/
EventPluginHub.injection.injectEventPluginsByName({
'SimpleEventPlugin': SimpleEventPlugin,
'EnterLeaveEventPlugin': EnterLeaveEventPlugin
});
/*
* This is a bit of a hack. We need to override the <form> element
* to be a composite component because IE8 does not bubble or capture
* submit to the top level. In order to make this work with our
* dependency graph we need to inject it here.
*/
ReactDOM.injection.injectComponentClasses({
form: ReactDOMForm
});
}
module.exports = {
inject: inject
};
},{"./ReactDOM":4,"./ReactDOMForm":24,"./DefaultEventPluginOrder":25,"./EnterLeaveEventPlugin":26,"./EventPluginHub":27,"./ReactInstanceHandles":21,"./SimpleEventPlugin":28}],7:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactCurrentOwner
*/
"use strict";
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],10:[function(require,module,exports){
/**
* 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.
*
* @providesModule invariant
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf style format and arguments to provide information about
* what broke and what you were expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition) {
if (!condition) {
throw new Error('Invariant Violation');
}
}
module.exports = invariant;
if (true) {
var invariantDev = function(condition, format, a, b, c, d, e, f) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
if (!condition) {
var args = [a, b, c, d, e, f];
var argIndex = 0;
throw new Error(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
}
};
module.exports = invariantDev;
}
},{}],13:[function(require,module,exports){
/**
* 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.
*
* @providesModule mixInto
*/
"use strict";
/**
* Simply copies properties to the prototype.
*/
var mixInto = function(constructor, methodBag) {
var methodName;
for (methodName in methodBag) {
if (!methodBag.hasOwnProperty(methodName)) {
continue;
}
constructor.prototype[methodName] = methodBag[methodName];
}
};
module.exports = mixInto;
},{}],14:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule ExecutionEnvironment
*/
/*jslint evil: true */
"use strict";
var canUseDOM = typeof window !== 'undefined';
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
isInWorker: !canUseDOM, // For now, this is true - might change in the future.
global: new Function('return this;')()
};
module.exports = ExecutionEnvironment;
})()
},{}],19:[function(require,module,exports){
/**
* 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.
*
* @providesModule objMapKeyVal
*/
"use strict";
/**
* Behaves the same as `objMap` but invokes func with the key first, and value
* second. Use `objMap` unless you need this special case.
* Invokes func as:
*
* func(key, value, iteration)
*
* @param {?object} obj Object to map keys over
* @param {!function} func Invoked for each key/val pair.
* @param {?*} context
* @return {?object} Result of mapping or null if obj is falsey
*/
function objMapKeyVal(obj, func, context) {
if (!obj) {
return null;
}
var i = 0;
var ret = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = func.call(context, key, obj[key], i++);
}
}
return ret;
}
module.exports = objMapKeyVal;
},{}],8:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactOwner
*/
"use strict";
var invariant = require("./invariant");
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: React.autoBind(function() {
* this.refs.custom.handleClick();
* }),
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function(object) {
return !!(
object &&
typeof object.attachRef === 'function' &&
typeof object.detachRef === 'function'
);
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function(component, ref, owner) {
invariant(
ReactOwner.isValidOwner(owner),
'addComponentAsRefTo(...): Only a ReactOwner can have refs.'
);
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function(component, ref, owner) {
invariant(
ReactOwner.isValidOwner(owner),
'removeComponentAsRefFrom(...): Only a ReactOwner can have refs.'
);
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.refs[ref] === component) {
owner.detachRef(ref);
}
},
/**
* A ReactComponent must mix this in to have refs.
*
* @lends {ReactOwner.prototype}
*/
Mixin: {
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function(ref, component) {
invariant(
component.isOwnedBy(this),
'attachRef(%s, ...): Only a component\'s owner can store a ref to it.',
ref
);
var refs = this.refs || (this.refs = {});
refs[ref] = component;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
delete this.refs[ref];
}
}
};
module.exports = ReactOwner;
},{"./invariant":10}],9:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactPropTransferer
*/
"use strict";
var emptyFunction = require("./emptyFunction");
var joinClasses = require("./joinClasses");
var merge = require("./merge");
/**
* Creates a transfer strategy that will merge prop values using the supplied
* `mergeStrategy`. If a prop was previously unset, this just sets it.
*
* @param {function} mergeStrategy
* @return {function}
*/
function createTransferStrategy(mergeStrategy) {
return function(props, key, value) {
if (!props.hasOwnProperty(key)) {
props[key] = value;
} else {
props[key] = mergeStrategy(props[key], value);
}
};
}
/**
* Transfer strategies dictate how props are transferred by `transferPropsTo`.
*/
var TransferStrategies = {
/**
* Never transfer the `ref` prop.
*/
ref: emptyFunction,
/**
* Transfer the `className` prop by merging them.
*/
className: createTransferStrategy(joinClasses),
/**
* Transfer the `style` prop (which is an object) by merging them.
*/
style: createTransferStrategy(merge)
};
/**
* ReactPropTransferer are capable of transferring props to another component
* using a `transferPropsTo` method.
*
* @class ReactPropTransferer
*/
var ReactPropTransferer = {
TransferStrategies: TransferStrategies,
/**
* @lends {ReactPropTransferer.prototype}
*/
Mixin: {
/**
* Transfer props from this component to a target component.
*
* Props that do not have an explicit transfer strategy will be transferred
* only if the target component does not already have the prop set.
*
* This is usually used to pass down props to a returned root component.
*
* @param {ReactComponent} component Component receiving the properties.
* @return {ReactComponent} The supplied `component`.
* @final
* @protected
*/
transferPropsTo: function(component) {
var props = {};
for (var thatKey in component.props) {
if (component.props.hasOwnProperty(thatKey)) {
props[thatKey] = component.props[thatKey];
}
}
for (var thisKey in this.props) {
if (!this.props.hasOwnProperty(thisKey)) {
continue;
}
var transferStrategy = TransferStrategies[thisKey];
if (transferStrategy) {
transferStrategy(props, thisKey, this.props[thisKey]);
} else if (!props.hasOwnProperty(thisKey)) {
props[thisKey] = this.props[thisKey];
}
}
component.props = props;
return component;
}
}
};
module.exports = ReactPropTransferer;
},{"./emptyFunction":29,"./joinClasses":30,"./merge":12}],11:[function(require,module,exports){
/**
* 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.
*
* @providesModule keyMirror
*/
"use strict";
var throwIf = require("./throwIf");
var NOT_OBJECT_ERROR = 'NOT_OBJECT_ERROR';
if (true) {
NOT_OBJECT_ERROR = 'keyMirror only works on objects';
}
/**
* Utility for constructing enums with keys being equal to the associated
* values, even when using advanced key crushing. This is useful for debugging,
* but also for using the values themselves as lookups into the enum.
* Example:
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor]
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*/
var keyMirror = function(obj) {
var ret = {};
var key;
throwIf(!(obj instanceof Object) || Array.isArray(obj), NOT_OBJECT_ERROR);
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"./throwIf":31}],12:[function(require,module,exports){
/**
* 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.
*
* @providesModule merge
*/
"use strict";
var mergeInto = require("./mergeInto");
/**
* Shallow merges two structures into a return value, without mutating either.
*
* @param {?object} one Optional object with properties to merge from.
* @param {?object} two Optional object with properties to merge from.
* @return {object} The shallow extension of one by two.
*/
var merge = function(one, two) {
var result = {};
mergeInto(result, one);
mergeInto(result, two);
return result;
};
module.exports = merge;
},{"./mergeInto":18}],15:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule ReactDOMIDOperations
* @typechecks
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = require("./CSSPropertyOperations");
var DOMChildrenOperations = require("./DOMChildrenOperations");
var DOMPropertyOperations = require("./DOMPropertyOperations");
var ReactDOMNodeCache = require("./ReactDOMNodeCache");
var getTextContentAccessor = require("./getTextContentAccessor");
var invariant = require("./invariant");
/**
* Errors for properties that should not be updated with `updatePropertyById()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
content: '`content` must be set using `updateTextContentByID()`.',
dangerouslySetInnerHTML:
'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor() || 'NA';
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactComponent.DOMIDOperations`.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function(id, name, value) {
var node = ReactDOMNodeCache.getCachedNodeByID(id);
invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
);
DOMPropertyOperations.setValueForProperty(node, name, value);
},
/**
* This should almost never be used instead of `updatePropertyByID()` due to
* the extra object allocation required by the API. That said, this is useful
* for batching up several operations across worker thread boundaries.
*
* @param {string} id ID of the node to update.
* @param {object} properties A mapping of valid property names.
* @internal
* @see {ReactDOMIDOperations.updatePropertyByID}
*/
updatePropertiesByID: function(id, properties) {
for (var name in properties) {
if (!properties.hasOwnProperty(name)) {
continue;
}
ReactDOMIDOperations.updatePropertiesByID(id, name, properties[name]);
}
},
/**
* Updates a DOM node with new style values.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: function(id, styles) {
var node = ReactDOMNodeCache.getCachedNodeByID(id);
CSSPropertyOperations.setValueForStyles(node, styles);
},
/**
* Updates a DOM node's innerHTML set by `props.dangerouslySetInnerHTML`.
*
* @param {string} id ID of the node to update.
* @param {object} html An HTML object with the `__html` property.
* @internal
*/
updateInnerHTMLByID: function(id, html) {
var node = ReactDOMNodeCache.getCachedNodeByID(id);
// HACK: IE8- normalize whitespace in innerHTML, removing leading spaces.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
node.innerHTML = (html && html.__html || '').replace(/^ /g, ' ');
},
/**
* Updates a DOM node's text content set by `props.content`.
*
* @param {string} id ID of the node to update.
* @param {string} content Text content.
* @internal
*/
updateTextContentByID: function(id, content) {
var node = ReactDOMNodeCache.getCachedNodeByID(id);
node[textContentAccessor] = content;
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function(id, markup) {
var node = ReactDOMNodeCache.getCachedNodeByID(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
ReactDOMNodeCache.purgeEntireCache();
},
/**
* TODO: We only actually *need* to purge the cache when we remove elements.
* Detect if any elements were removed instead of blindly purging.
*/
manageChildrenByParentID: function(parentID, domOperations) {
var parent = ReactDOMNodeCache.getCachedNodeByID(parentID);
DOMChildrenOperations.manageChildren(parent, domOperations);
ReactDOMNodeCache.purgeEntireCache();
},
setTextNodeValueAtIndexByParentID: function(parentID, index, value) {
var parent = ReactDOMNodeCache.getCachedNodeByID(parentID);
DOMChildrenOperations.setTextNodeValueAtIndex(parent, index, value);
}
};
module.exports = ReactDOMIDOperations;
})()
},{"./CSSPropertyOperations":32,"./DOMChildrenOperations":33,"./DOMPropertyOperations":34,"./ReactDOMNodeCache":35,"./getTextContentAccessor":36,"./invariant":10}],16:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactReconcileTransaction
* @typechecks
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var PooledClass = require("./PooledClass");
var ReactEvent = require("./ReactEvent");
var ReactInputSelection = require("./ReactInputSelection");
var ReactOnDOMReady = require("./ReactOnDOMReady");
var Transaction = require("./Transaction");
var mixInto = require("./mixInto");
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactEvent` before the
* reconciliation.
*/
initialize: function() {
var currentlyEnabled = ReactEvent.isEnabled();
ReactEvent.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled The enabled status of `ReactEvent`
* before the reconciliation occured. `close` restores the previous value.
*/
close: function(previouslyEnabled) {
ReactEvent.setEnabled(previouslyEnabled);
}
};
/**
* Provides a `ReactOnDOMReady` queue for collecting `onDOMReady` callbacks
* during the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactOnDOMReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function() {
this.reactOnDOMReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [
SELECTION_RESTORATION,
EVENT_SUPPRESSION,
ON_DOM_READY_QUEUEING
];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction() {
this.reinitializeTransaction();
this.reactOnDOMReady = ReactOnDOMReady.getPooled(null);
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap proceedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
if (ExecutionEnvironment.canUseDOM) {
return TRANSACTION_WRAPPERS;
} else {
return [];
}
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
* TODO: convert to ReactOnDOMReady
*/
getReactOnDOMReady: function() {
return this.reactOnDOMReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
ReactOnDOMReady.release(this.reactOnDOMReady);
this.reactOnDOMReady = null;
}
};
mixInto(ReactReconcileTransaction, Transaction.Mixin);
mixInto(ReactReconcileTransaction, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"./ExecutionEnvironment":14,"./PooledClass":37,"./ReactEvent":20,"./ReactInputSelection":38,"./ReactOnDOMReady":39,"./Transaction":40,"./mixInto":13}],17:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactNativeComponent
* @typechecks
*/
"use strict";
var CSSPropertyOperations = require("./CSSPropertyOperations");
var DOMPropertyOperations = require("./DOMPropertyOperations");
var ReactComponent = require("./ReactComponent");
var ReactEvent = require("./ReactEvent");
var ReactMultiChild = require("./ReactMultiChild");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var flattenChildren = require("./flattenChildren");
var invariant = require("./invariant");
var keyOf = require("./keyOf");
var merge = require("./merge");
var mixInto = require("./mixInto");
var putListener = ReactEvent.putListener;
var registrationNames = ReactEvent.registrationNames;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = {'string': true, 'number': true};
var CONTENT = keyOf({content: null});
var DANGEROUSLY_SET_INNER_HTML = keyOf({dangerouslySetInnerHTML: null});
var STYLE = keyOf({style: null});
/**
* @param {?object} props
*/
function assertValidProps(props) {
if (!props) {
return;
}
// Note the use of `!=` which checks for null or undefined.
var hasChildren = props.children != null ? 1 : 0;
var hasContent = props.content != null ? 1 : 0;
var hasInnerHTML = props.dangerouslySetInnerHTML != null ? 1 : 0;
invariant(
hasChildren + hasContent + hasInnerHTML <= 1,
'Can only set one of `children`, `props.content`, or ' +
'`props.dangerouslySetInnerHTML`.'
);
invariant(
props.style == null || typeof props.style === 'object',
'The `style` prop expects a mapping from style properties to values, ' +
'not a string.'
);
}
/**
* @constructor ReactNativeComponent
* @extends ReactComponent
* @extends ReactMultiChild
*/
function ReactNativeComponent(tag, omitClose) {
this._tagOpen = '<' + tag + ' ';
this._tagClose = omitClose ? '' : '</' + tag + '>';
this.tagName = tag.toUpperCase();
}
ReactNativeComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {string} rootID The root DOM ID for this node.
* @param {ReactReconcileTransaction} transaction
* @return {string} The computed markup.
*/
mountComponent: function(rootID, transaction) {
ReactComponent.Mixin.mountComponent.call(this, rootID, transaction);
assertValidProps(this.props);
return (
this._createOpenTagMarkup() +
this._createContentMarkup(transaction) +
this._tagClose
);
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkup: function() {
var props = this.props;
var ret = this._tagOpen;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNames[propKey]) {
putListener(this._rootNodeID, propKey, propValue);
} else {
if (propKey === STYLE) {
if (propValue) {
propValue = props.style = merge(props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var markup =
DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
if (markup) {
ret += ' ' + markup;
}
}
}
return ret + ' id="' + this._rootNodeID + '">';
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction} transaction
* @return {string} Content markup.
*/
_createContentMarkup: function(transaction) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = this.props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var contentToUse = this.props.content != null ? this.props.content :
CONTENT_TYPES[typeof this.props.children] ? this.props.children : null;
var childrenToUse = contentToUse != null ? null : this.props.children;
if (contentToUse != null) {
return escapeTextForBrowser(contentToUse);
} else if (childrenToUse != null) {
return this.mountMultiChild(
flattenChildren(childrenToUse),
transaction
);
}
}
return '';
},
/**
* Controls a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @internal
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
*/
receiveProps: function(nextProps, transaction) {
invariant(
this._rootNodeID,
'Trying to control a native dom element without a backing id'
);
assertValidProps(nextProps);
ReactComponent.Mixin.receiveProps.call(this, nextProps, transaction);
this._updateDOMProperties(nextProps);
this._updateDOMChildren(nextProps, transaction);
this.props = nextProps;
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} nextProps
*/
_updateDOMProperties: function(nextProps) {
var lastProps = this.props;
for (var propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
nextProp = nextProps.style = merge(nextProp);
}
var styleUpdates;
for (var styleName in nextProp) {
if (!nextProp.hasOwnProperty(styleName)) {
continue;
}
if (!lastProp || lastProp[styleName] !== nextProp[styleName]) {
if (!styleUpdates) {
styleUpdates = {};
}
styleUpdates[styleName] = nextProp[styleName];
}
}
if (styleUpdates) {
ReactComponent.DOMIDOperations.updateStylesByID(
this._rootNodeID,
styleUpdates
);
}
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
var lastHtml = lastProp && lastProp.__html;
var nextHtml = nextProp && nextProp.__html;
if (lastHtml !== nextHtml) {
ReactComponent.DOMIDOperations.updateInnerHTMLByID(
this._rootNodeID,
nextProp
);
}
} else if (propKey === CONTENT) {
ReactComponent.DOMIDOperations.updateTextContentByID(
this._rootNodeID,
'' + nextProp
);
} else if (registrationNames[propKey]) {
putListener(this._rootNodeID, propKey, nextProp);
} else {
ReactComponent.DOMIDOperations.updatePropertyByID(
this._rootNodeID,
propKey,
nextProp
);
}
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMChildren: function(nextProps, transaction) {
var thisPropsContentType = typeof this.props.content;
var thisPropsContentEmpty =
this.props.content == null || thisPropsContentType === 'boolean';
var nextPropsContentType = typeof nextProps.content;
var nextPropsContentEmpty =
nextProps.content == null || nextPropsContentType === 'boolean';
var lastUsedContent = !thisPropsContentEmpty ? this.props.content :
CONTENT_TYPES[typeof this.props.children] ? this.props.children : null;
var contentToUse = !nextPropsContentEmpty ? nextProps.content :
CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
// Note the use of `!=` which checks for null or undefined.
var lastUsedChildren =
lastUsedContent != null ? null : this.props.children;
var childrenToUse = contentToUse != null ? null : nextProps.children;
if (contentToUse != null) {
var childrenRemoved = lastUsedChildren != null && childrenToUse == null;
if (childrenRemoved) {
this.updateMultiChild(null, transaction);
}
if (lastUsedContent !== contentToUse) {
ReactComponent.DOMIDOperations.updateTextContentByID(
this._rootNodeID,
'' + contentToUse
);
}
} else {
var contentRemoved = lastUsedContent != null && contentToUse == null;
if (contentRemoved) {
ReactComponent.DOMIDOperations.updateTextContentByID(
this._rootNodeID,
''
);
}
this.updateMultiChild(flattenChildren(nextProps.children), transaction);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function() {
ReactComponent.Mixin.unmountComponent.call(this);
this.unmountMultiChild();
ReactEvent.deleteAllListeners(this._rootNodeID);
}
};
mixInto(ReactNativeComponent, ReactComponent.Mixin);
mixInto(ReactNativeComponent, ReactNativeComponent.Mixin);
mixInto(ReactNativeComponent, ReactMultiChild.Mixin);
module.exports = ReactNativeComponent;
},{"./CSSPropertyOperations":32,"./DOMPropertyOperations":34,"./ReactComponent":3,"./ReactEvent":20,"./ReactMultiChild":41,"./escapeTextForBrowser":42,"./flattenChildren":43,"./invariant":10,"./keyOf":44,"./merge":12,"./mixInto":13}],18:[function(require,module,exports){
/**
* 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.
*
* @providesModule mergeInto
* @typechecks
*/
"use strict";
var mergeHelpers = require("./mergeHelpers");
var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg;
/**
* Shallow merges two structures by mutating the first parameter.
*
* @param {object} one Object to be merged into.
* @param {?object} two Optional object with properties to merge from.
*/
function mergeInto(one, two) {
checkMergeObjectArg(one);
if (two != null) {
checkMergeObjectArg(two);
for (var key in two) {
if (!two.hasOwnProperty(key)) {
continue;
}
one[key] = two[key];
}
}
}
module.exports = mergeInto;
},{"./mergeHelpers":45}],20:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactEvent
*/
"use strict";
var BrowserEnv = require("./BrowserEnv");
var EventConstants = require("./EventConstants");
var EventPluginHub = require("./EventPluginHub");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var NormalizedEventListener = require("./NormalizedEventListener");
var invariant = require("./invariant");
var isEventSupported = require("./isEventSupported");
var registrationNames = EventPluginHub.registrationNames;
var topLevelTypes = EventConstants.topLevelTypes;
var listen = NormalizedEventListener.listen;
var capture = NormalizedEventListener.capture;
/**
* `ReactEvent` is used to attach top-level event listeners. For example:
*
* ReactEvent.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*/
/**
* Overview of React and the event system:
*
* .
* +-------------+ .
* | DOM | .
* +-------------+ . +-----------+
* + . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|-------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +------------.---->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | | . | |<---+|Plugin | |other plugin|
* | +------------.---------+ | +-----------+ | utilities |
* | | | . | | | +------------+
* | | | . +---|----------+
* | | | . | ^ +-----------+
* | | | . | | |Enter/Leave|
* +-----| ------+ . | +-------+|Plugin |
* | . v +-----------+
* + . +--------+
* +-------------+ . |callback|
* | application | . |registry|
* |-------------| . +--------+
* | | .
* | | .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when mounting
* `onmousemove` events at some node that was not the document element. The
* symptoms were that if your mouse is not moving over something contained
* within that mount point (for example on the background) the top-level
* listeners for `onmousemove` won't be called. However, if you register the
* `mousemove` on the document object, then it will of course catch all
* `mousemove`s. This along with iOS quirks, justifies restricting top-level
* listeners to the document object only, at least for these movement types of
* events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @see http://www.quirksmode.org/dom/events/keys.html.
*/
var _isListening = false;
var EVENT_LISTEN_MISUSE;
var WORKER_DISABLE;
if (true) {
EVENT_LISTEN_MISUSE =
'You must register listeners at the top of the document, only once - ' +
'and only in the main UI thread of a browser - if you are attempting ' +
'listen in a worker, the framework is probably doing something wrong ' +
'and you should report this immediately.';
WORKER_DISABLE =
'Cannot disable event listening in Worker thread. This is likely a ' +
'bug in the framework. Please report immediately.';
}
/**
* Traps top-level events that bubble. Delegates to the main dispatcher
* `handleTopLevel` after performing some basic normalization via
* `TopLevelCallbackCreator.createTopLevelCallback`.
*/
function trapBubbledEvent(topLevelType, handlerBaseName, onWhat) {
listen(
onWhat,
handlerBaseName,
ReactEvent.TopLevelCallbackCreator.createTopLevelCallback(topLevelType)
);
}
/**
* Traps a top-level event by using event capturing.
*/
function trapCapturedEvent(topLevelType, handlerBaseName, onWhat) {
capture(
onWhat,
handlerBaseName,
ReactEvent.TopLevelCallbackCreator.createTopLevelCallback(topLevelType)
);
}
/**
* Listens to document scroll and window resize events that may change the
* document scroll values. We store those results so as to discourage
* application code from asking the DOM itself which could trigger additional
* reflows.
*/
function registerDocumentScrollListener() {
listen(window, 'scroll', function(nativeEvent) {
if (nativeEvent.target === window) {
BrowserEnv.refreshAuthoritativeScrollValues();
}
});
}
function registerDocumentResizeListener() {
listen(window, 'resize', function(nativeEvent) {
if (nativeEvent.target === window) {
BrowserEnv.refreshAuthoritativeScrollValues();
}
});
}
/**
* Summary of `ReactEvent` event handling:
*
* - We trap low level 'top-level' events.
*
* - We dedupe cross-browser event names into these 'top-level types' so that
* `DOMMouseScroll` or `mouseWheel` both become `topMouseWheel`.
*
* - At this point we have native browser events with the top-level type that
* was used to catch it at the top-level.
*
* - We continuously stream these native events (and their respective top-level
* types) to the event plugin system `EventPluginHub` and ask the plugin
* system if it was able to extract `AbstractEvent` objects. `AbstractEvent`
* objects are the events that applications actually deal with - they are not
* native browser events but cross-browser wrappers.
*
* - When returning the `AbstractEvent` objects, `EventPluginHub` will make
* sure each abstract event is annotated with "dispatches", which are the
* sequence of listeners (and IDs) that care about the event.
*
* - These `AbstractEvent` objects are fed back into the event plugin system,
* which in turn executes these dispatches.
*
* @private
*/
function listenAtTopLevel(touchNotMouse) {
invariant(
!_isListening,
'listenAtTopLevel(...): Cannot setup top-level listener more than once.'
);
var mountAt = document;
registerDocumentScrollListener();
registerDocumentResizeListener();
trapBubbledEvent(topLevelTypes.topMouseOver, 'mouseover', mountAt);
trapBubbledEvent(topLevelTypes.topMouseDown, 'mousedown', mountAt);
trapBubbledEvent(topLevelTypes.topMouseUp, 'mouseup', mountAt);
trapBubbledEvent(topLevelTypes.topMouseMove, 'mousemove', mountAt);
trapBubbledEvent(topLevelTypes.topMouseOut, 'mouseout', mountAt);
trapBubbledEvent(topLevelTypes.topClick, 'click', mountAt);
trapBubbledEvent(topLevelTypes.topDoubleClick, 'dblclick', mountAt);
trapBubbledEvent(topLevelTypes.topMouseWheel, 'mousewheel', mountAt);
if (touchNotMouse) {
trapBubbledEvent(topLevelTypes.topTouchStart, 'touchstart', mountAt);
trapBubbledEvent(topLevelTypes.topTouchEnd, 'touchend', mountAt);
trapBubbledEvent(topLevelTypes.topTouchMove, 'touchmove', mountAt);
trapBubbledEvent(topLevelTypes.topTouchCancel, 'touchcancel', mountAt);
}
trapBubbledEvent(topLevelTypes.topKeyUp, 'keyup', mountAt);
trapBubbledEvent(topLevelTypes.topKeyPress, 'keypress', mountAt);
trapBubbledEvent(topLevelTypes.topKeyDown, 'keydown', mountAt);
trapBubbledEvent(topLevelTypes.topChange, 'change', mountAt);
trapBubbledEvent(
topLevelTypes.topDOMCharacterDataModified,
'DOMCharacterDataModified',
mountAt
);
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
trapBubbledEvent(topLevelTypes.topMouseWheel, 'DOMMouseScroll', mountAt);
// IE < 9 doesn't support capturing so just trap the bubbled event there.
if (isEventSupported('scroll', true)) {
trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
trapBubbledEvent(topLevelTypes.topScroll, 'scroll', window);
}
if (isEventSupported('focus', true)) {
trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
}
}
/**
* This is the heart of `ReactEvent`. It simply streams the top-level native
* events to `EventPluginHub`.
*
* @param {object} topLevelType Record from `EventConstants`.
* @param {Event} nativeEvent A Standard Event with fixed `target` property.
* @param {DOMElement} renderedTarget Element of interest to the framework.
* @param {string} renderedTargetID string ID of `renderedTarget`.
* @internal
*/
function handleTopLevel(
topLevelType,
nativeEvent,
renderedTargetID,
renderedTarget) {
var abstractEvents = EventPluginHub.extractAbstractEvents(
topLevelType,
nativeEvent,
renderedTargetID,
renderedTarget
);
// The event queue being processed in the same cycle allows preventDefault.
EventPluginHub.enqueueAbstractEvents(abstractEvents);
EventPluginHub.processAbstractEventQueue();
}
function setEnabled(enabled) {
invariant(
ExecutionEnvironment.canUseDOM,
'setEnabled(...): Cannot toggle event listening in a Worker thread. This ' +
'is likely a bug in the framework. Please report immediately.'
);
ReactEvent.TopLevelCallbackCreator.setEnabled(enabled);
}
function isEnabled() {
return ReactEvent.TopLevelCallbackCreator.isEnabled();
}
/**
* Ensures that top-level event delegation listeners are listening at `mountAt`.
* There are issues with listening to both touch events and mouse events on the
* top-level, so we make the caller choose which one to listen to. (If there's a
* touch top-level listeners, anchors don't receive clicks for some reason, and
* only in some cases).
*
* @param {boolean} touchNotMouse Listen to touch events instead of mouse.
* @param {object} TopLevelCallbackCreator Module that can create top-level
* callback handlers.
* @internal
*/
function ensureListening(touchNotMouse, TopLevelCallbackCreator) {
invariant(
ExecutionEnvironment.canUseDOM,
'ensureListening(...): Cannot toggle event listening in a Worker thread. ' +
'This is likely a bug in the framework. Please report immediately.'
);
if (!_isListening) {
ReactEvent.TopLevelCallbackCreator = TopLevelCallbackCreator;
listenAtTopLevel(touchNotMouse);
_isListening = true;
}
}
var ReactEvent = {
TopLevelCallbackCreator: null, // Injectable callback creator.
handleTopLevel: handleTopLevel,
setEnabled: setEnabled,
isEnabled: isEnabled,
ensureListening: ensureListening,
registrationNames: registrationNames,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteAllListeners: EventPluginHub.deleteAllListeners,
trapBubbledEvent: trapBubbledEvent,
trapCapturedEvent: trapCapturedEvent
};
module.exports = ReactEvent;
},{"./BrowserEnv":46,"./EventConstants":47,"./EventPluginHub":27,"./ExecutionEnvironment":14,"./NormalizedEventListener":48,"./invariant":10,"./isEventSupported":49}],21:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactInstanceHandles
*/
"use strict";
var getDOMNodeID = require("./getDOMNodeID");
var invariant = require("./invariant");
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 100;
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isMarker(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || (
id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR
);
}
/**
* True if the supplied `node` is rendered by React.
*
* @param {DOMElement} node DOM Element to check.
* @return {boolean} True if the DOM Element appears to be rendered by React.
* @private
*/
function isRenderedByReact(node) {
var id = getDOMNodeID(node);
return id && id.charAt(0) === SEPARATOR;
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function parentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
invariant(
start !== stop,
'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
start
);
var ancestorID = ReactInstanceHandles.getFirstCommonAncestorID(start, stop);
var traverseUp = ancestorID === stop;
invariant(
traverseUp || ancestorID === start,
'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
'not have a parent path.',
start,
stop
);
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? parentID : ReactInstanceHandles.nextDescendantID;
for (var id = start; /* until break */; id = traverse(id, stop)) {
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
cb(id, traverseUp, arg);
}
if (id === stop) {
// Only break //after// visiting `stop`.
break;
}
invariant(
depth++ < MAX_TREE_DEPTH,
'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' +
'traversing the React DOM ID tree. This may be due to malformed IDs: %s',
start, stop
);
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
separator: SEPARATOR,
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component.
*
* @param {DOMElement} node
* @return {?DOMElement}
* @internal
*/
getFirstReactDOM: function(node) {
var current = node;
while (current && current.parentNode !== current) {
if (isRenderedByReact(current)) {
return current;
}
current = current.parentNode;
}
return null;
},
/**
* Finds a node with the supplied `id` inside of the supplied `ancestorNode`.
* Exploits the ID naming scheme to perform the search quickly.
*
* @param {DOMElement} ancestorNode Search from this root.
* @pararm {string} id ID of the DOM representation of the component.
* @return {?DOMElement} DOM element with the supplied `id`, if one exists.
* @internal
*/
findComponentRoot: function(ancestorNode, id) {
var child = ancestorNode.firstChild;
while (child) {
if (id === child.id) {
return child;
} else if (id.indexOf(child.id) === 0) {
return ReactInstanceHandles.findComponentRoot(child, id);
}
child = child.nextSibling;
}
// Effectively: return null;
},
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @internal
*/
getFirstCommonAncestorID: function(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isMarker(oneID, i) && isMarker(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
invariant(
isValidID(longestCommonID),
'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
oneID,
twoID,
longestCommonID
);
return longestCommonID;
},
/**
* Creates a DOM ID to use when mounting React components.
*
* @param {number} mountPointCount The count of React renders so far.
* @return {string} React root ID.
* @internal
*/
getReactRootID: function(mountPointCount) {
return '.reactRoot[' + mountPointCount + ']';
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function(id) {
var regexResult = /\.reactRoot\[[^\]]+\]/.exec(id);
return regexResult && regexResult[0];
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) {
var longestCommonID = ReactInstanceHandles.getFirstCommonAncestorID(
leaveID,
enterID
);
if (longestCommonID !== leaveID) {
traverseParentPath(leaveID, longestCommonID, cb, upArg, false, true);
}
if (longestCommonID !== enterID) {
traverseParentPath(longestCommonID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function(targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @internal
*/
nextDescendantID: function(ancestorID, destinationID) {
invariant(
isValidID(ancestorID) && isValidID(destinationID),
'nextDescendantID(%s, %s): Received an invalid React DOM ID.',
ancestorID,
destinationID
);
var longestCommonID = ReactInstanceHandles.getFirstCommonAncestorID(
ancestorID,
destinationID
);
invariant(
longestCommonID === ancestorID,
'nextDescendantID(...): React has made an invalid assumption about the ' +
'DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
ancestorID,
destinationID
);
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
for (var i = start; i < destinationID.length; i++) {
if (isMarker(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
};
module.exports = ReactInstanceHandles;
},{"./getDOMNodeID":50,"./invariant":10}],22:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule ReactEventTopLevelCallback
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var ReactEvent = require("./ReactEvent");
var ReactInstanceHandles = require("./ReactInstanceHandles");
var getDOMNodeID = require("./getDOMNodeID");
var _topLevelListenersEnabled = true;
var ReactEventTopLevelCallback = {
/**
* @param {boolean} enabled Whether or not all callbacks that have ever been
* created with this module should be enabled.
*/
setEnabled: function(enabled) {
_topLevelListenersEnabled = !!enabled;
},
isEnabled: function() {
return _topLevelListenersEnabled;
},
/**
* For a given `topLevelType`, creates a callback that could be added as a
* listener to the document. That top level callback will simply fix the
* native events before invoking `handleTopLevel`.
*
* - Raw native events cannot be trusted to describe their targets correctly
* so we expect that the argument to the nested function has already been
* fixed. But the `target` property may not be something of interest to
* React, so we find the most suitable target. But even at that point, DOM
* Elements (the target ) can't be trusted to describe their IDs correctly
* so we obtain the ID in a reliable manner and pass it to
* `handleTopLevel`. The target/id that we found to be relevant to our
* framework are called `renderedTarget`/`renderedTargetID` respectively.
*/
createTopLevelCallback: function(topLevelType) {
return function(fixedNativeEvent) {
if (!_topLevelListenersEnabled) {
return;
}
var renderedTarget = ReactInstanceHandles.getFirstReactDOM(
fixedNativeEvent.target
) || ExecutionEnvironment.global;
var renderedTargetID = getDOMNodeID(renderedTarget);
var event = fixedNativeEvent;
var target = renderedTarget;
ReactEvent.handleTopLevel(topLevelType, event, renderedTargetID, target);
};
}
};
module.exports = ReactEventTopLevelCallback;
})()
},{"./ExecutionEnvironment":14,"./ReactEvent":20,"./ReactInstanceHandles":21,"./getDOMNodeID":50}],23:[function(require,module,exports){
/**
* 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.
*
* @providesModule $
*/
var ge = require("./ge");
/**
* Find a node by ID.
*
* If your application code depends on the existence of the element, use $,
* which will throw if the element doesn't exist.
*
* If you're not sure whether or not the element exists, use ge instead, and
* manually check for the element's existence in your application code.
*/
function $(arg) {
var element = ge(arg);
if (!element) {
if (typeof arg == 'undefined') {
arg = 'undefined';
} else if (arg === null) {
arg = 'null';
}
throw new Error(
'Tried to get element "' + arg.toString() + '" but it is not present ' +
'on the page.'
);
}
return element;
}
module.exports = $;
},{"./ge":51}],24:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactDOMForm
*/
"use strict";
var ReactCompositeComponent = require("./ReactCompositeComponent");
var ReactDOM = require("./ReactDOM");
var ReactEvent = require("./ReactEvent");
var EventConstants = require("./EventConstants");
// Store a reference to the <form> `ReactNativeComponent`.
var form = ReactDOM.form;
/**
* Since onSubmit doesn't bubble OR capture on the top level in IE8, we need
* to capture it on the <form> element itself. There are lots of hacks we could
* do to accomplish this, but the most reliable is to make <form> a
* composite component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMForm = ReactCompositeComponent.createClass({
render: function() {
// TODO: Instead of using `ReactDOM` directly, we should use JSX. However,
// `jshint` fails to parse JSX so in order for linting to work in the open
// source repo, we need to just use `ReactDOM.form`.
return this.transferPropsTo(form(null, this.props.children));
},
componentDidMount: function(node) {
ReactEvent.trapBubbledEvent(
EventConstants.topLevelTypes.topSubmit,
'submit',
node
);
}
});
module.exports = ReactDOMForm;
},{"./ReactCompositeComponent":2,"./ReactDOM":4,"./ReactEvent":20,"./EventConstants":47}],25:[function(require,module,exports){
/**
* 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.
*
* @providesModule DefaultEventPluginOrder
*/
"use strict";
var keyOf = require("./keyOf");
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [
keyOf({ResponderEventPlugin: null}),
keyOf({SimpleEventPlugin: null}),
keyOf({TapEventPlugin: null}),
keyOf({EnterLeaveEventPlugin: null}),
keyOf({AnalyticsEventPlugin: null})
];
module.exports = DefaultEventPluginOrder;
},{"./keyOf":44}],26:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule EnterLeaveEventPlugin
*/
"use strict";
var EventPropagators = require("./EventPropagators");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var AbstractEvent = require("./AbstractEvent");
var EventConstants = require("./EventConstants");
var ReactInstanceHandles = require("./ReactInstanceHandles");
var getDOMNodeID = require("./getDOMNodeID");
var keyOf = require("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactInstanceHandles.getFirstReactDOM;
var abstractEventTypes = {
mouseEnter: {registrationName: keyOf({onMouseEnter: null})},
mouseLeave: {registrationName: keyOf({onMouseLeave: null})}
};
/**
* For almost every interaction we care about, there will be a top level
* `mouseOver` and `mouseOut` event that occur so we can usually only pay
* attention to one of the two (we'll pay attention to the `mouseOut` event) to
* avoid extracting a duplicate event. However, there's one interaction where
* there will be no `mouseOut` event to rely on - mousing from outside the
* browser *into* the chrome. We detect this scenario and only in that case, we
* use the `mouseOver` event.
*
* @see EventPluginHub.extractAbstractEvents
*/
var extractAbstractEvents = function(
topLevelType,
nativeEvent,
renderedTargetID,
renderedTarget) {
if (topLevelType === topLevelTypes.topMouseOver &&
(nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return;
}
if (topLevelType !== topLevelTypes.topMouseOut &&
topLevelType !== topLevelTypes.topMouseOver){
return null; // Must not be a mouse in or mouse out - ignoring.
}
var to, from;
if (topLevelType === topLevelTypes.topMouseOut) {
to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) ||
ExecutionEnvironment.global;
from = renderedTarget;
} else {
to = renderedTarget;
from = ExecutionEnvironment.global;
}
// Nothing pertains to our managed components.
if (from === to ) {
return;
}
var fromID = from ? getDOMNodeID(from) : '';
var toID = to ? getDOMNodeID(to) : '';
var leave = AbstractEvent.getPooled(
abstractEventTypes.mouseLeave,
fromID,
topLevelType,
nativeEvent
);
var enter = AbstractEvent.getPooled(
abstractEventTypes.mouseEnter,
toID,
topLevelType,
nativeEvent
);
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
return [leave, enter];
};
var EnterLeaveEventPlugin = {
abstractEventTypes: abstractEventTypes,
extractAbstractEvents: extractAbstractEvents
};
module.exports = EnterLeaveEventPlugin;
})()
},{"./EventPropagators":52,"./ExecutionEnvironment":14,"./AbstractEvent":53,"./EventConstants":47,"./ReactInstanceHandles":21,"./getDOMNodeID":50,"./keyOf":44}],27:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule EventPluginHub
*/
"use strict";
var AbstractEvent = require("./AbstractEvent");
var CallbackRegistry = require("./CallbackRegistry");
var EventPluginUtils = require("./EventPluginUtils");
var EventPropagators = require("./EventPropagators");
var ExecutionEnvironment = require("./ExecutionEnvironment");
var accumulate = require("./accumulate");
var forEachAccumulated = require("./forEachAccumulated");
var keyMirror = require("./keyMirror");
var merge = require("./merge");
var throwIf = require("./throwIf");
var deleteListener = CallbackRegistry.deleteListener;
var ERRORS = keyMirror({
DOUBLE_REGISTER: null,
DOUBLE_ENQUEUE: null,
DEPENDENCY_ERROR: null
});
if (true) {
ERRORS.DOUBLE_REGISTER =
'You\'ve included an event plugin that extracts an ' +
'event type with the exact same or identity as an event that ' +
'had previously been injected - or, one of the registration names ' +
'used by an plugin has already been used.';
ERRORS.DOUBLE_ENQUEUE =
'During the processing of events, more events were enqueued. This ' +
'is strange and should not happen. Please report immediately. ';
ERRORS.DEPENDENCY_ERROR =
'You have either attempted to load an event plugin that has no ' +
'entry in EventPluginOrder, or have attempted to extract events ' +
'when some critical dependencies have not yet been injected.';
}
/**
* EventPluginHub: To see a diagram and explanation of the overall architecture
* of the plugin hub system, @see ReactEvents.js
*/
/**
* Injected Dependencies:
*/
var injection = {
/**
* [required] Dependency of `EventPropagators`.
*/
injectInstanceHandle: function(InjectedInstanceHandle) {
EventPropagators.injection.injectInstanceHandle(InjectedInstanceHandle);
},
/**
* `EventPluginOrder`: [optional] Provides deterministic ordering of
* `EventPlugin`s. Ordering decoupled from the injection of actual
* plugins so that there is always a deterministic and permanent ordering
* regardless of the plugins that happen to become packaged, or applications
* that happen to inject on-the-fly event plugins.
*/
EventPluginOrder: null,
injectEventPluginOrder: function(InjectedEventPluginOrder) {
injection.EventPluginOrder = InjectedEventPluginOrder;
injection._recomputePluginsList();
},
/**
* `EventPlugins`: [optional][lazy-loadable] Plugins that must be listed in
* the `EventPluginOrder` injected dependency. The list of plugins may grow as
* custom plugins are injected into the system at page as part of the
* initialization process, or even after the initialization process (on-the-
* fly). Plugins injected into the hub have an opportunity to infer abstract
* events when top level events are streamed through the `EventPluginHub`.
*/
plugins: [],
injectEventPluginsByName: function(pluginsByName) {
injection.pluginsByName = merge(injection.pluginsByName, pluginsByName);
injection._recomputePluginsList();
},
/**
* A reference of all injected plugins by their name. Both plugins and
* `EventPluginOrder` can be injected on-the-fly. Any time either dependency
* is (re)injected, the resulting list of plugins in correct order is
* recomputed.
*/
pluginsByName: {},
_recomputePluginsList: function() {
var injectPluginByName = function(name, PluginModule) {
var pluginIndex = injection.EventPluginOrder.indexOf(name);
throwIf(pluginIndex === -1, ERRORS.DEPENDENCY_ERROR + name);
if (!injection.plugins[pluginIndex]) {
injection.plugins[pluginIndex] = PluginModule;
for (var eventName in PluginModule.abstractEventTypes) {
var eventType = PluginModule.abstractEventTypes[eventName];
recordAllRegistrationNames(eventType, PluginModule);
}
}
};
if (injection.EventPluginOrder) { // Else, do when plugin order injected
var injectedPluginsByName = injection.pluginsByName;
for (var name in injectedPluginsByName) {
injectPluginByName(name, injectedPluginsByName[name]);
}
}
}
};
/**
* `renderedTarget`: We'll refer to the concept of a "rendered target". Any
* framework code that uses the `EventPluginHub` will stream events to the
* `EventPluginHub`. In order for registered plugins to make sense of the native
* events, it helps to allow plugins to not only have access to the native
* `Event` object but also the notion of a "rendered target", which is the
* conceptual target `Element` of the `Event` that the framework (user of
* `EventPluginHub`) deems as being the "important" target.
*/
/**
* Keeps track of all valid "registration names" (`onClick` etc). We expose
* these structures to other modules, who will always see updates that we apply
* to these structures. They should never have a desire to mutate these.
*/
var registrationNames = {};
/**
* This prevents the need for clients to call `Object.keys(registrationNames)`
* every time they want to loop through the possible registration names.
*/
var registrationNamesArr = [];
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var abstractEventQueue = [];
/**
* Records all the registration names that the event plugin makes available
* to the general event system. These are things like
* `onClick`/`onClickCapture`.
*/
function recordAllRegistrationNames(eventType, PluginModule) {
var phaseName;
var phasedRegistrationNames = eventType.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (phaseName in phasedRegistrationNames) {
if (!phasedRegistrationNames.hasOwnProperty(phaseName)) {
continue;
}
if (true) {
throwIf(
registrationNames[phasedRegistrationNames[phaseName]],
ERRORS.DOUBLE_REGISTER
);
}
registrationNames[phasedRegistrationNames[phaseName]] = PluginModule;
registrationNamesArr.push(phasedRegistrationNames[phaseName]);
}
} else if (eventType.registrationName) {
if (true) {
throwIf(
registrationNames[eventType.registrationName],
ERRORS.DOUBLE_REGISTER
);
}
registrationNames[eventType.registrationName] = PluginModule;
registrationNamesArr.push(eventType.registrationName);
}
}
/**
* A hacky way to reverse engineer which event plugin module created an
* AbstractEvent.
* @param {AbstractEvent} abstractEvent to look at
*/
function getPluginModuleForAbstractEvent(abstractEvent) {
if (abstractEvent.type.registrationName) {
return registrationNames[abstractEvent.type.registrationName];
} else {
for (var phase in abstractEvent.type.phasedRegistrationNames) {
if (!abstractEvent.type.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = registrationNames[
abstractEvent.type.phasedRegistrationNames[phase]
];
if (PluginModule) {
return PluginModule;
}
}
}
return null;
}
var deleteAllListeners = function(domID) {
var ii;
for (ii = 0; ii < registrationNamesArr.length; ii++) {
deleteListener(domID, registrationNamesArr[ii]);
}
};
/**
* Accepts the stream of top level native events, and gives every registered
* plugin an opportunity to extract `AbstractEvent`s with annotated dispatches.
*
* @param {Enum} topLevelType Record from `EventConstants`.
* @param {Event} nativeEvent A Standard Event with fixed `target` property.
* @param {Element} renderedTarget Element of interest to the framework, usually
* the same as `nativeEvent.target` but occasionally an element immediately
* above `nativeEvent.target` (the first DOM node recognized as one "rendered"
* by the framework at hand.)
* @param {string} renderedTargetID string ID of `renderedTarget`.
*/
var extractAbstractEvents =
function(topLevelType, nativeEvent, renderedTargetID, renderedTarget) {
var abstractEvents;
var plugins = injection.plugins;
var len = plugins.length;
for (var i = 0; i < len; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
var extractedAbstractEvents =
possiblePlugin &&
possiblePlugin.extractAbstractEvents(
topLevelType,
nativeEvent,
renderedTargetID,
renderedTarget
);
if (extractedAbstractEvents) {
abstractEvents = accumulate(abstractEvents, extractedAbstractEvents);
}
}
return abstractEvents;
};
var enqueueAbstractEvents = function(abstractEvents) {
if (abstractEvents) {
abstractEventQueue = accumulate(abstractEventQueue, abstractEvents);
}
};
/**
* Executes a single abstract event dispatch. Returns a value, but this return
* value doesn't make much sense when executing dispatches for a list of a
* events. However, if a plugin executes a single dispatch, mostly bypassing
* `EventPluginHub`, it can execute dispatches directly and assign special
* meaning to the return value. So this will return the result of executing the
* dispatch, though for most use cases, it gets dropped.
*/
var executeDispatchesAndRelease = function(abstractEvent) {
if (abstractEvent) {
var PluginModule = getPluginModuleForAbstractEvent(abstractEvent);
var pluginExecuteDispatch = PluginModule && PluginModule.executeDispatch;
EventPluginUtils.executeDispatchesInOrder(
abstractEvent,
pluginExecuteDispatch || EventPluginUtils.executeDispatch
);
AbstractEvent.release(abstractEvent);
}
};
/**
* Sets `abstractEventQueue` to null before processing it, so that we can tell
* if in the process of processing events, more were enqueued. We throw if we
* find that any were enqueued though this use case could be supported in the
* future. For now, throwing an error as it's something we don't expect to
* occur.
*/
var processAbstractEventQueue = function() {
var processingAbstractEventQueue = abstractEventQueue;
abstractEventQueue = null;
forEachAccumulated(processingAbstractEventQueue, executeDispatchesAndRelease);
if (true) {
throwIf(abstractEventQueue, ERRORS.DOUBLE_ENQUEUE);
}
};
/**
* Provides a unified interface for an arbitrary and dynamic set of event
* plugins. Loosely, a hub, where several "event plugins" may act as a single
* event plugin behind the facade of `EventPluginHub`. Each event plugin injects
* themselves into the HUB, and will immediately become operable upon injection.
*
* @constructor EventPluginHub
*/
var EventPluginHub = {
registrationNames: registrationNames,
registrationNamesArr: registrationNamesArr,
putListener: CallbackRegistry.putListener,
getListener: CallbackRegistry.getListener,
deleteAllListeners: deleteAllListeners,
extractAbstractEvents: extractAbstractEvents,
enqueueAbstractEvents: enqueueAbstractEvents,
processAbstractEventQueue: processAbstractEventQueue,
injection: injection
};
if (ExecutionEnvironment.canUseDOM) {
window.EventPluginHub = EventPluginHub;
}
module.exports = EventPluginHub;
})()
},{"./AbstractEvent":53,"./CallbackRegistry":54,"./EventPluginUtils":55,"./EventPropagators":52,"./ExecutionEnvironment":14,"./accumulate":56,"./forEachAccumulated":57,"./keyMirror":11,"./merge":12,"./throwIf":31}],28:[function(require,module,exports){
/**
* 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.
*
* @providesModule SimpleEventPlugin
*/
"use strict";
var AbstractEvent = require("./AbstractEvent");
var EventConstants = require("./EventConstants");
var EventPropagators = require("./EventPropagators");
var keyOf = require("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var SimpleEventPlugin = {
abstractEventTypes: {
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseDown: true}),
captured: keyOf({onMouseDownCapture: true})
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseUp: true}),
captured: keyOf({onMouseUpCapture: true})
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseMove: true}),
captured: keyOf({onMouseMoveCapture: true})
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({onDoubleClick: true}),
captured: keyOf({onDoubleClickCapture: true})
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({onClick: true}),
captured: keyOf({onClickCapture: true})
}
},
mouseWheel: {
phasedRegistrationNames: {
bubbled: keyOf({onMouseWheel: true}),
captured: keyOf({onMouseWheelCapture: true})
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchStart: true}),
captured: keyOf({onTouchStartCapture: true})
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchEnd: true}),
captured: keyOf({onTouchEndCapture: true})
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchCancel: true}),
captured: keyOf({onTouchCancelCapture: true})
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({onTouchMove: true}),
captured: keyOf({onTouchMoveCapture: true})
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyUp: true}),
captured: keyOf({onKeyUpCapture: true})
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyPress: true}),
captured: keyOf({onKeyPressCapture: true})
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({onKeyDown: true}),
captured: keyOf({onKeyDownCapture: true})
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({onFocus: true}),
captured: keyOf({onFocusCapture: true})
}
},
blur: {
phasedRegistrationNames: {
bubbled: keyOf({onBlur: true}),
captured: keyOf({onBlurCapture: true})
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({onScroll: true}),
captured: keyOf({onScrollCapture: true})
}
},
change: {
phasedRegistrationNames: {
bubbled: keyOf({onChange: true}),
captured: keyOf({onChangeCapture: true})
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({onSubmit: true}),
captured: keyOf({onSubmitCapture: true})
}
},
DOMCharacterDataModified: {
phasedRegistrationNames: {
bubbled: keyOf({onDOMCharacterDataModified: true}),
captured: keyOf({onDOMCharacterDataModifiedCapture: true})
}
}
},
/**
* Same as the default implementation, except cancels the event when return
* value is false.
* @param {AbstractEvent} AbstractEvent to handle
* @param {function} Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
executeDispatch: function(abstractEvent, listener, domID) {
var returnValue = listener(abstractEvent, domID);
if (returnValue === false) {
abstractEvent.stopPropagation();
abstractEvent.preventDefault();
}
},
/**
* @see EventPluginHub.extractAbstractEvents
*/
extractAbstractEvents:
function(topLevelType, nativeEvent, renderedTargetID, renderedTarget) {
var data;
var abstractEventType =
SimpleEventPlugin.topLevelTypesToAbstract[topLevelType];
if (!abstractEventType) {
return null;
}
switch(topLevelType) {
case topLevelTypes.topMouseWheel:
data = AbstractEvent.normalizeMouseWheelData(nativeEvent);
break;
case topLevelTypes.topScroll:
data = AbstractEvent.normalizeScrollDataFromTarget(renderedTarget);
break;
case topLevelTypes.topClick:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topChange:
case topLevelTypes.topDOMCharacterDataModified:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseUp:
case topLevelTypes.topMouseMove:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
case topLevelTypes.topTouchEnd:
data = AbstractEvent.normalizePointerData(nativeEvent);
break;
default:
data = null;
}
var abstractEvent = AbstractEvent.getPooled(
abstractEventType,
renderedTargetID,
topLevelType,
nativeEvent,
data
);
EventPropagators.accumulateTwoPhaseDispatches(abstractEvent);
return abstractEvent;
}
};
SimpleEventPlugin.topLevelTypesToAbstract = {
topMouseDown: SimpleEventPlugin.abstractEventTypes.mouseDown,
topMouseUp: SimpleEventPlugin.abstractEventTypes.mouseUp,
topMouseMove: SimpleEventPlugin.abstractEventTypes.mouseMove,
topClick: SimpleEventPlugin.abstractEventTypes.click,
topDoubleClick: SimpleEventPlugin.abstractEventTypes.doubleClick,
topMouseWheel: SimpleEventPlugin.abstractEventTypes.mouseWheel,
topTouchStart: SimpleEventPlugin.abstractEventTypes.touchStart,
topTouchEnd: SimpleEventPlugin.abstractEventTypes.touchEnd,
topTouchMove: SimpleEventPlugin.abstractEventTypes.touchMove,
topTouchCancel: SimpleEventPlugin.abstractEventTypes.touchCancel,
topKeyUp: SimpleEventPlugin.abstractEventTypes.keyUp,
topKeyPress: SimpleEventPlugin.abstractEventTypes.keyPress,
topKeyDown: SimpleEventPlugin.abstractEventTypes.keyDown,
topFocus: SimpleEventPlugin.abstractEventTypes.focus,
topBlur: SimpleEventPlugin.abstractEventTypes.blur,
topScroll: SimpleEventPlugin.abstractEventTypes.scroll,
topChange: SimpleEventPlugin.abstractEventTypes.change,
topSubmit: SimpleEventPlugin.abstractEventTypes.submit,
topDOMCharacterDataModified:
SimpleEventPlugin.abstractEventTypes.DOMCharacterDataModified
};
module.exports = SimpleEventPlugin;
},{"./AbstractEvent":53,"./EventConstants":47,"./EventPropagators":52,"./keyOf":44}],30:[function(require,module,exports){
/**
* 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.
*
* @providesModule joinClasses
* @typechecks
*/
"use strict";
/**
* Combines multiple className strings into one.
* http://jsperf.com/joinclasses-args-vs-array
*
* @param {...?string} classes
* @return {string}
*/
function joinClasses(className/*, ... */) {
if (!className) {
className = '';
}
var nextClass;
var argLength = arguments.length;
if (argLength > 1) {
for (var ii = 1; ii < argLength; ii++) {
nextClass = arguments[ii];
nextClass && (className += ' ' + nextClass);
}
}
return className;
}
module.exports = joinClasses;
},{}],31:[function(require,module,exports){
/**
* 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.
*
* @providesModule throwIf
*/
"use strict";
var throwIf = function(condition, err) {
if (condition) {
throw new Error(err);
}
};
module.exports = throwIf;
},{}],37:[function(require,module,exports){
/**
* 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.
*
* @providesModule PooledClass
*/
"use strict";
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function(copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var fiveArgumentPooler = function(a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function(instance) {
var Klass = this;
if (instance.destructor) {
instance.destructor();
}
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function(CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{}],38:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactInputSelection
*/
"use strict";
// It is not safe to read the document.activeElement property in IE if there's
// nothing focused.
function getActiveElement() {
try {
return document.activeElement;
} catch (e) {
}
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function(elem) {
return elem && (
(elem.nodeName === 'INPUT' && elem.type === 'text') ||
elem.nodeName === 'TEXTAREA' ||
elem.contentEditable === 'true'
);
},
getSelectionInformation: function() {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange:
ReactInputSelection.hasSelectionCapabilities(focusedElem) ?
ReactInputSelection.getSelection(focusedElem) :
null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function(priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem &&
document.getElementById(priorFocusedElem.id)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(
priorFocusedElem,
priorSelectionRange
);
}
priorFocusedElem.focus();
}
},
/**
* @getSelection: Gets the selection bounds of a textarea or input.
* -@input: Look up selection bounds of this input or textarea
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function(input) {
var range;
if (input.contentEditable === 'true' && window.getSelection) {
range = window.getSelection().getRangeAt(0);
var commonAncestor = range.commonAncestorContainer;
if (commonAncestor && commonAncestor.nodeType === 3) {
commonAncestor = commonAncestor.parentNode;
}
if (commonAncestor !== input) {
return {start: 0, end: 0};
} else {
return {start: range.startOffset, end: range.endOffset};
}
}
if (!document.selection) {
// Mozilla, Safari, etc.
return {start: input.selectionStart, end: input.selectionEnd};
}
range = document.selection.createRange();
if (range.parentElement() !== input) {
// There can only be one selection per document in IE, so if the
// containing element of the document's selection isn't our text field,
// our text field must have no selection.
return {start: 0, end: 0};
}
var length = input.value.length;
if (input.nodeName === 'INPUT') {
return {
start: -range.moveStart('character', -length),
end: -range.moveEnd('character', -length)
};
} else {
var range2 = range.duplicate();
range2.moveToElementText(input);
range2.setEndPoint('StartToEnd', range);
var end = length - range2.text.length;
range2.setEndPoint('StartToStart', range);
return {
start: length - range2.text.length,
end: end
};
}
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@rangeObj Object of same form that is returned from get*
*/
setSelection: function(input, rangeObj) {
var range;
var start = rangeObj.start;
var end = rangeObj.end;
if (typeof end === 'undefined') {
end = start;
}
if (document.selection) {
// IE is inconsistent about character offsets when it comes to carriage
// returns, so we need to manually take them into account
if (input.tagName === 'TEXTAREA') {
var cr_before =
(input.value.slice(0, start).match(/\r/g) || []).length;
var cr_inside =
(input.value.slice(start, end).match(/\r/g) || []).length;
start -= cr_before;
end -= cr_before + cr_inside;
}
range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
if (input.contentEditable === 'true') {
if (input.childNodes.length === 1) {
range = document.createRange();
range.setStart(input.childNodes[0], start);
range.setEnd(input.childNodes[0], end);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
} else {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
input.focus();
}
}
}
};
module.exports = ReactInputSelection;
},{}],44:[function(require,module,exports){
/**
* 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.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without loosing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
},{}],46:[function(require,module,exports){
/**
* 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.
*
* @providesModule BrowserEnv
*/
"use strict";
/**
* A place to share/cache browser/chrome level computations.
*/
var BrowserEnv = {
currentScrollLeft: 0,
currentScrollTop: 0,
browserInfo: null,
refreshAuthoritativeScrollValues: function() {
BrowserEnv.currentScrollLeft =
document.body.scrollLeft + document.documentElement.scrollLeft;
BrowserEnv.currentScrollTop =
document.body.scrollTop + document.documentElement.scrollTop;
}
};
module.exports = BrowserEnv;
},{}],50:[function(require,module,exports){
/**
* 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.
*
* @providesModule getDOMNodeID
*/
"use strict";
/**
* Accessing "id" or calling getAttribute('id') on a form element can return its
* control whose name or ID is "id". However, not all DOM nodes support
* `getAttributeNode` (document - which is not a form) so that is checked first.
*
* @param {Element} domNode DOM node element to return ID of.
* @returns {string} The ID of `domNode`.
*/
function getDOMNodeID(domNode) {
if (domNode.getAttributeNode) {
var attributeNode = domNode.getAttributeNode('id');
return attributeNode && attributeNode.value || '';
} else {
return domNode.id || '';
}
}
module.exports = getDOMNodeID;
},{}],51:[function(require,module,exports){
/**
* 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.
*
* @providesModule ge
*/
/**
* Find a node by ID. Optionally search a sub-tree outside of the document
*
* Use ge if you're not sure whether or not the element exists. You can test
* for existence yourself in your application code.
*
* If your application code depends on the existence of the element, use $
* instead, which will throw in DEV if the element doesn't exist.
*/
function ge(arg, root, tag) {
return typeof arg != 'string' ? arg :
!root ? document.getElementById(arg) :
_geFromSubtree(arg, root, tag);
}
function _geFromSubtree(id, root, tag) {
var elem, children, ii;
if (_getNodeID(root) == id) {
return root;
} else if (root.getElementsByTagName) {
// All Elements implement this, which does an iterative DFS, which is
// faster than recursion and doesn't run into stack depth issues.
children = root.getElementsByTagName(tag || '*');
for (ii = 0; ii < children.length; ii++) {
if (_getNodeID(children[ii]) == id) {
return children[ii];
}
}
} else {
// DocumentFragment does not implement getElementsByTagName, so
// recurse over its children. Its children must be Elements, so
// each child will use the getElementsByTagName case instead.
children = root.childNodes;
for (ii = 0; ii < children.length; ii++) {
elem = _geFromSubtree(id, children[ii]);
if (elem) {
return elem;
}
}
}
return null;
}
/**
* Return the ID value for a given node. This allows us to avoid issues
* with forms that contain inputs with name="id".
*
* @return string (null if attribute not set)
*/
function _getNodeID(node) {
// #document and #document-fragment do not have getAttributeNode.
var id = node.getAttributeNode && node.getAttributeNode('id');
return id ? id.value : null;
}
module.exports = ge;
},{}],54:[function(require,module,exports){
/**
* 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.
*
* @providesModule CallbackRegistry
*/
"use strict";
var listenerBank = {};
/**
* Stores "listeners" by `registrationName`/`id`. There should be at most one
* "listener" per `registrationName/id` in the `listenerBank`.
* Access listeners via `listenerBank[registrationName][id]`
*
* @constructor CallbackRegistry
*/
var CallbackRegistry = {
/**
* Stores `listener` at `listenerBank[registrationName][id]. Is idempotent.
* @param {string} domID The id of the DOM node.
* @param {string} registrationName The name of listener (`onClick` etc).
* @param {Function} listener The callback to to store.
*/
putListener: function(id, registrationName, listener) {
var bankForRegistrationName =
listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
},
/**
* @param {string} id.
* @param {string} registrationName Name of registration (`onClick` etc).
* @return {Function?} The Listener
*/
getListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes the listener from the registration bank.
* @param {string} id
* @param {string} registrationName (`onClick` etc).
*/
deleteListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
// This is needed for tests only. Do not use in real life
__purge: function() {
listenerBank = {};
}
};
module.exports = CallbackRegistry;
},{}],57:[function(require,module,exports){
/**
* 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.
*
* @providesModule forEachAccumulated
*/
"use strict";
/**
* @param {array} an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function(arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
};
module.exports = forEachAccumulated;
},{}],29:[function(require,module,exports){
/**
* 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.
*
* @providesModule emptyFunction
*/
var copyProperties = require("./copyProperties");
function makeEmptyFunction(arg) {
return function() {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
function emptyFunction() {}
copyProperties(emptyFunction, {
thatReturns: makeEmptyFunction,
thatReturnsFalse: makeEmptyFunction(false),
thatReturnsTrue: makeEmptyFunction(true),
thatReturnsNull: makeEmptyFunction(null),
thatReturnsThis: function() { return this; },
thatReturnsArgument: function(arg) { return arg; },
mustImplement: function(module, property) {
return function() {
if (true) {
throw new Error(module + '.' + property + ' must be implemented!');
}
};
}
});
module.exports = emptyFunction;
},{"./copyProperties":58}],32:[function(require,module,exports){
/**
* 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.
*
* @providesModule CSSPropertyOperations
* @typechecks
*/
"use strict";
var dangerousStyleValue = require("./dangerousStyleValue");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var hyphenate = require("./hyphenate");
var memoizeStringOnly = require("./memoizeStringOnly");
var processStyleName = memoizeStringOnly(function(styleName) {
return escapeTextForBrowser(hyphenate(styleName));
});
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
*
* @param {object} styles
* @return {string}
*/
createMarkupForStyles: function(styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (typeof styleValue !== 'undefined') {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
return serialized;
},
/**
* Sets the value for multiple styles on a node.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function(node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
style[styleName] = dangerousStyleValue(styleName, styleValue);
}
}
};
module.exports = CSSPropertyOperations;
},{"./dangerousStyleValue":59,"./escapeTextForBrowser":42,"./hyphenate":60,"./memoizeStringOnly":61}],33:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule DOMChildrenOperations
*/
"use strict";
var Danger = require("./Danger");
var insertNodeAt = require("./insertNodeAt");
var keyOf = require("./keyOf");
var throwIf = require("./throwIf");
var NON_INCREASING_OPERATIONS;
if (true) {
NON_INCREASING_OPERATIONS =
'DOM child management operations must be provided in order ' +
'of increasing destination index. This is likely an issue with ' +
'the core framework.';
}
var MOVE_NODE_AT_ORIG_INDEX = keyOf({moveFrom: null});
var INSERT_MARKUP = keyOf({insertMarkup: null});
var REMOVE_AT = keyOf({removeAt: null});
/**
* In order to carry out movement of DOM nodes without knowing their IDs, we
* have to first store knowledge about nodes' original indices before beginning
* to carry out the sequence of operations. Once we begin the sequence, the DOM
* indices in future instructions are no longer valid.
*
* @param {Element} parent Parent DOM node.
* @param {Object} childOperations Description of child operations.
* @returns {Array?} Sparse array containing elements by their current index in
* the DOM.
*/
var _getNodesByOriginalIndex = function(parent, childOperations) {
var nodesByOriginalIndex; // Sparse array.
var childOperation;
var origIndex;
for (var i = 0; i < childOperations.length; i++) {
childOperation = childOperations[i];
if (MOVE_NODE_AT_ORIG_INDEX in childOperation) {
nodesByOriginalIndex = nodesByOriginalIndex || [];
origIndex = childOperation.moveFrom;
nodesByOriginalIndex[origIndex] = parent.childNodes[origIndex];
} else if (REMOVE_AT in childOperation) {
nodesByOriginalIndex = nodesByOriginalIndex || [];
origIndex = childOperation.removeAt;
nodesByOriginalIndex[origIndex] = parent.childNodes[origIndex];
}
}
return nodesByOriginalIndex;
};
/**
* Removes DOM elements from their parent, or moved.
* @param {Element} parent Parent DOM node.
* @param {Array} nodesByOriginalIndex Child nodes by their original index
* (potentially sparse.)
*/
var _removeChildrenByOriginalIndex = function(parent, nodesByOriginalIndex) {
for (var j = 0; j < nodesByOriginalIndex.length; j++) {
var nodeToRemove = nodesByOriginalIndex[j];
if (nodeToRemove) { // We used a sparse array.
parent.removeChild(nodesByOriginalIndex[j]);
}
}
};
/**
* Once all nodes that will be removed or moved - are removed from the parent
* node, we can begin the process of placing nodes into their final locations.
* We must perform all operations in the order of the final DOM index -
* otherwise, we couldn't count on the fact that an insertion at index X, will
* remain at index X. This will iterate through the child operations, adding
* content where needed, skip over removals (they've already been removed) and
* insert "moved" Elements that were previously removed. The "moved" elements
* are only temporarily removed from the parent, so that index calculations can
* be manageable and perform well in the cases that matter.
*/
var _placeNodesAtDestination =
function(parent, childOperations, nodesByOriginalIndex) {
var origNode;
var finalIndex;
var lastFinalIndex = -1;
var childOperation;
for (var k = 0; k < childOperations.length; k++) {
childOperation = childOperations[k];
if (MOVE_NODE_AT_ORIG_INDEX in childOperation) {
origNode = nodesByOriginalIndex[childOperation.moveFrom];
finalIndex = childOperation.finalIndex;
insertNodeAt(parent, origNode, finalIndex);
if (true) {
throwIf(finalIndex <= lastFinalIndex, NON_INCREASING_OPERATIONS);
lastFinalIndex = finalIndex;
}
} else if (REMOVE_AT in childOperation) {
} else if (INSERT_MARKUP in childOperation) {
finalIndex = childOperation.finalIndex;
var markup = childOperation.insertMarkup;
Danger.dangerouslyInsertMarkupAt(parent, markup, finalIndex);
if (true) {
throwIf(finalIndex <= lastFinalIndex, NON_INCREASING_OPERATIONS);
lastFinalIndex = finalIndex;
}
}
}
};
var manageChildren = function(parent, childOperations) {
var nodesByOriginalIndex = _getNodesByOriginalIndex(parent, childOperations);
if (nodesByOriginalIndex) {
_removeChildrenByOriginalIndex(parent, nodesByOriginalIndex);
}
_placeNodesAtDestination(parent, childOperations, nodesByOriginalIndex);
};
var setTextNodeValueAtIndex = function(parent, index, val) {
parent.childNodes[index].nodeValue = val;
};
/**
* Also reexport all of the dangerous functions. It helps to have all dangerous
* functions located in a single module `Danger`.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
manageChildren: manageChildren,
setTextNodeValueAtIndex: setTextNodeValueAtIndex
};
module.exports = DOMChildrenOperations;
})()
},{"./Danger":62,"./insertNodeAt":63,"./keyOf":44,"./throwIf":31}],34:[function(require,module,exports){
/**
* 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.
*
* @providesModule DOMPropertyOperations
* @typechecks
*/
"use strict";
var DOMProperty = require("./DOMProperty");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var memoizeStringOnly = require("./memoizeStringOnly");
var processAttributeNameAndPrefix = memoizeStringOnly(function(name) {
return escapeTextForBrowser(name) + '="';
});
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function(name, value) {
if (DOMProperty.isStandardName[name]) {
if (value == null || DOMProperty.hasBooleanValue[name] && !value) {
return '';
}
var attributeName = DOMProperty.getAttributeName[name];
return processAttributeNameAndPrefix(attributeName) +
escapeTextForBrowser(value) + '"';
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return processAttributeNameAndPrefix(name) +
escapeTextForBrowser(value) + '"';
} else {
return null;
}
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function(node, name, value) {
if (DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, value);
} else if (DOMProperty.mustUseAttribute[name]) {
if (DOMProperty.hasBooleanValue[name] && !value) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
node.setAttribute(DOMProperty.getAttributeName[name], value);
}
} else {
var propName = DOMProperty.getPropertyName[name];
if (!DOMProperty.hasSideEffects[name] || node[propName] !== value) {
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.setAttribute(name, value);
}
}
};
module.exports = DOMPropertyOperations;
},{"./DOMProperty":64,"./escapeTextForBrowser":42,"./memoizeStringOnly":61}],35:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactDOMNodeCache
*/
"use strict";
var ReactMount = require("./ReactMount");
var nodeCache = {};
/**
* DOM node cache only intended for use by React. Placed into a shared module so
* that both read and write utilities may benefit from a shared cache.
*/
var ReactDOMNodeCache = {
/**
* Releases fast id lookups (node/style cache). This implementation is
* aggressive with purging because the bookkeeping associated with doing fine
* grained deleted from the cache may outweight the benefits of the cache. The
* heuristic that should be used to purge is 'any time anything is deleted'.
* Typically this means that a large amount of content is being replaced and
* several elements would need purging regardless. It's also a time when an
* application is likely not in the middle of a "smooth operation" (such as
* animating/scrolling).
*/
purgeEntireCache: function() {
nodeCache = {};
return nodeCache;
},
getCachedNodeByID: function(id) {
return nodeCache[id] ||
(nodeCache[id] =
document.getElementById(id) ||
ReactMount.findReactRenderedDOMNodeSlow(id));
}
};
module.exports = ReactDOMNodeCache;
},{"./ReactMount":5}],36:[function(require,module,exports){
/**
* 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.
*
* @providesModule getTextContentAccessor
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
contentKey = 'innerText' in document.createElement('div') ?
'innerText' :
'textContent';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"./ExecutionEnvironment":14}],39:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactOnDOMReady
*/
"use strict";
var PooledClass = require("./PooledClass");
var mixInto = require("./mixInto");
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `ReactOnDOMReady.getPooled()`.
*
* @param {?array<function>} initialCollection
* @class ReactOnDOMReady
* @implements PooledClass
* @internal
*/
function ReactOnDOMReady(initialCollection) {
this._queue = initialCollection || null;
}
mixInto(ReactOnDOMReady, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked. This is used
* to enqueue calls to `componentDidMount` and `componentDidUpdate`.
*
* @param {ReactComponent} component Component being rendered.
* @param {function(DOMElement)} callback Invoked when `notifyAll` is invoked.
* @internal
*/
enqueue: function(component, callback) {
this._queue = this._queue || [];
this._queue.push({component: component, callback: callback});
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function() {
var queue = this._queue;
if (queue) {
this._queue = null;
for (var i = 0, l = queue.length; i < l; i++) {
var component = queue[i].component;
var callback = queue[i].callback;
callback.call(component, component.getDOMNode());
}
queue.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function() {
this._queue = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(ReactOnDOMReady);
module.exports = ReactOnDOMReady;
},{"./PooledClass":37,"./mixInto":13}],40:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule Transaction
*/
"use strict";
var throwIf = require("./throwIf");
var DUAL_TRANSACTION = 'DUAL_TRANSACTION';
var MISSING_TRANSACTION = 'MISSING_TRANSACTION';
if (true) {
DUAL_TRANSACTION =
'Cannot initialize transaction when there is already an outstanding ' +
'transaction. Common causes of this are trying to render a component ' +
'when you are already rendering a component or attempting a state ' +
'transition while in a render function. Another possibility is that ' +
'you are rendering new content (or state transitioning) in a ' +
'componentDidRender callback. If this is not the case, please report the ' +
'issue immediately.';
MISSING_TRANSACTION =
'Cannot close transaction when there is none open.';
}
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be ran while it is already being ran. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Bonus:
* - Reports timing metrics by method name and wrapper index.
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidRender` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM upates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function() {
this.transactionWrappers = this.getTransactionWrappers();
if (!this.wrapperInitData) {
this.wrapperInitData = [];
} else {
this.wrapperInitData.length = 0;
}
if (!this.timingMetrics) {
this.timingMetrics = {};
}
this.timingMetrics.methodInvocationTime = 0;
if (!this.timingMetrics.wrapperInitTimes) {
this.timingMetrics.wrapperInitTimes = [];
} else {
this.timingMetrics.wrapperInitTimes.length = 0;
}
if (!this.timingMetrics.wrapperCloseTimes) {
this.timingMetrics.wrapperCloseTimes = [];
} else {
this.timingMetrics.wrapperCloseTimes.length = 0;
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function() {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} args... Arguments to pass to the method (optional).
* Helps prevent need to bind in many cases.
* @returns Return value from `method`.
*/
perform: function(method, scope, a, b, c, d, e, f) {
throwIf(this.isInTransaction(), DUAL_TRANSACTION);
var memberStart = Date.now();
var err = null;
var ret;
try {
this.initializeAll();
ret = method.call(scope, a, b, c, d, e, f);
} catch (ie_requires_catch) {
err = ie_requires_catch;
} finally {
var memberEnd = Date.now();
this.methodInvocationTime += (memberEnd - memberStart);
try {
this.closeAll();
} catch (closeAllErr) {
err = err || closeAllErr;
}
}
if (err) {
throw err;
}
return ret;
},
initializeAll: function() {
this._isInTransaction = true;
var transactionWrappers = this.transactionWrappers;
var wrapperInitTimes = this.timingMetrics.wrapperInitTimes;
var err = null;
for (var i = 0; i < transactionWrappers.length; i++) {
var initStart = Date.now();
var wrapper = transactionWrappers[i];
try {
this.wrapperInitData[i] =
wrapper.initialize ? wrapper.initialize.call(this) : null;
} catch (initErr) {
err = err || initErr; // Remember the first error.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
} finally {
var curInitTime = wrapperInitTimes[i];
var initEnd = Date.now();
wrapperInitTimes[i] = (curInitTime || 0) + (initEnd - initStart);
}
}
if (err) {
throw err;
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function() {
throwIf(!this.isInTransaction(), MISSING_TRANSACTION);
var transactionWrappers = this.transactionWrappers;
var wrapperCloseTimes = this.timingMetrics.wrapperCloseTimes;
var err = null;
for (var i = 0; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var closeStart = Date.now();
var initData = this.wrapperInitData[i];
try {
if (initData !== Transaction.OBSERVED_ERROR) {
wrapper.close && wrapper.close.call(this, initData);
}
} catch (closeErr) {
err = err || closeErr; // Remember the first error.
} finally {
var closeEnd = Date.now();
var curCloseTime = wrapperCloseTimes[i];
wrapperCloseTimes[i] = (curCloseTime || 0) + (closeEnd - closeStart);
}
}
this.wrapperInitData.length = 0;
this._isInTransaction = false;
if (err) {
throw err;
}
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occured.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
})()
},{"./throwIf":31}],41:[function(require,module,exports){
(function(){/**
* 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.
*
* @providesModule ReactMultiChild
*/
"use strict";
var ReactComponent = require("./ReactComponent");
/**
* Given a `curChild` and `newChild`, determines if `curChild` should be managed
* as it exists, as opposed to being destroyed and/or replaced.
* @param {?ReactComponent} curChild
* @param {?ReactComponent} newChild
* @return {!boolean} Whether or not `curChild` should be updated with
* `newChild`'s props
*/
function shouldManageExisting(curChild, newChild) {
return curChild && newChild && curChild.constructor === newChild.constructor;
}
/**
* `ReactMultiChild` provides common functionality for components that have
* multiple children. Standard `ReactCompositeComponent`s do not currently have
* multiple children. `ReactNativeComponent`s do, however. Other specially
* reconciled components will also have multiple children. Contains three
* internally used properties that are used to keep track of state throughout
* the `updateMultiChild` process.
*
* @class ReactMultiChild
*/
/**
* @lends `ReactMultiChildMixin`.
*/
var ReactMultiChildMixin = {
enqueueMarkupAt: function(markup, insertAt) {
this.domOperations = this.domOperations || [];
this.domOperations.push({insertMarkup: markup, finalIndex: insertAt});
},
enqueueMove: function(originalIndex, finalIndex) {
this.domOperations = this.domOperations || [];
this.domOperations.push({moveFrom: originalIndex, finalIndex: finalIndex});
},
enqueueUnmountChildByName: function(name, removeChild) {
if (ReactComponent.isValidComponent(removeChild)) {
this.domOperations = this.domOperations || [];
this.domOperations.push({removeAt: removeChild._domIndex});
removeChild.unmountComponent && removeChild.unmountComponent();
delete this._renderedChildren[name];
}
},
/**
* Process any pending DOM operations that have been accumulated when updating
* the UI. By default, we execute the injected `DOMIDOperations` module's
* `manageChildrenByParentID` which does executes the DOM operations without
* any animation. It can be used as a reference implementation for special
* animation based implementations.
*
* @abstract
*/
processChildDOMOperationsQueue: function() {
if (this.domOperations) {
ReactComponent.DOMIDOperations
.manageChildrenByParentID(this._rootNodeID, this.domOperations);
this.domOperations = null;
}
},
unmountMultiChild: function() {
var renderedChildren = this._renderedChildren;
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name) && renderedChildren[name]) {
var renderedChild = renderedChildren[name];
renderedChild.unmountComponent && renderedChild.unmountComponent();
}
}
this._renderedChildren = null;
},
/**
* Generates markup for a component that holds multiple children. #todo: Allow
* all `ReactMultiChildMixin`s to support having arrays of children without a
* container node. This current implementation may assume that children exist
* at domIndices [0, parentNode.length].
*
* Has side effects of (likely) causing events to be registered. Also, every
* component instance may only be rendered once.
*
* @param {?Object} children Flattened children object.
* @return {!String} The rendered markup.
*/
mountMultiChild: function(children, transaction) {
var accum = '';
var index = 0;
for (var name in children) {
var child = children[name];
if (children.hasOwnProperty(name) && child) {
accum += child.mountComponent(
this._rootNodeID + '.' + name,
transaction
);
child._domIndex = index;
index++;
}
}
this._renderedChildren = children; // children are in just the right form!
this.domOperations = null;
return accum;
},
/**
* Reconciles new children with old children in three phases.
*
* - Adds new content while updating existing children that should remain.
* - Remove children that are no longer present in the next children.
* - As a very last step, moves existing dom structures around.
* - (Comment 1) `curChildrenDOMIndex` is the largest index of the current
* rendered children that appears in the next children and did not need to
* be "moved".
* - (Comment 2) This is the key insight. If any non-removed child's previous
* index is less than `curChildrenDOMIndex` it must be moved.
*
* @param {?Object} children Flattened children object.
*/
updateMultiChild: function(nextChildren, transaction) {
if (!nextChildren && !this._renderedChildren) {
return;
} else if (nextChildren && !this._renderedChildren) {
this._renderedChildren = {}; // lazily allocate backing store with nothing
} else if (!nextChildren && this._renderedChildren) {
nextChildren = {};
}
var rootDomIdDot = this._rootNodeID + '.';
var markupBuffer = null; // Accumulate adjacent new children markup.
var numPendingInsert = 0; // How many root nodes are waiting in markupBuffer
var loopDomIndex = 0; // Index of loop through new children.
var curChildrenDOMIndex = 0; // See (Comment 1)
for (var name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {continue;}
var curChild = this._renderedChildren[name];
var nextChild = nextChildren[name];
if (shouldManageExisting(curChild, nextChild)) {
if (markupBuffer) {
this.enqueueMarkupAt(markupBuffer, loopDomIndex - numPendingInsert);
markupBuffer = null;
}
numPendingInsert = 0;
if (curChild._domIndex < curChildrenDOMIndex) { // (Comment 2)
this.enqueueMove(curChild._domIndex, loopDomIndex);
}
curChildrenDOMIndex = Math.max(curChild._domIndex, curChildrenDOMIndex);
!nextChild.props.isStatic &&
curChild.receiveProps(nextChild.props, transaction);
curChild._domIndex = loopDomIndex;
} else {
if (curChild) { // !shouldUpdate && curChild => delete
this.enqueueUnmountChildByName(name, curChild);
curChildrenDOMIndex =
Math.max(curChild._domIndex, curChildrenDOMIndex);
}
if (nextChild) { // !shouldUpdate && nextChild => insert
this._renderedChildren[name] = nextChild;
var nextMarkup =
nextChild.mountComponent(rootDomIdDot + name, transaction);
markupBuffer = markupBuffer ? markupBuffer + nextMarkup : nextMarkup;
numPendingInsert++;
nextChild._domIndex = loopDomIndex;
}
}
loopDomIndex = nextChild ? loopDomIndex + 1 : loopDomIndex;
}
if (markupBuffer) {
this.enqueueMarkupAt(markupBuffer, loopDomIndex - numPendingInsert);
}
for (var childName in this._renderedChildren) { // from other direction
if (!this._renderedChildren.hasOwnProperty(childName)) { continue; }
var child = this._renderedChildren[childName];
if (child && !nextChildren[childName]) {
this.enqueueUnmountChildByName(childName, child);
}
}
this.processChildDOMOperationsQueue();
}
};
var ReactMultiChild = {
Mixin: ReactMultiChildMixin
};
module.exports = ReactMultiChild;
})()
},{"./ReactComponent":3}],42:[function(require,module,exports){
/**
* 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.
*
* @providesModule escapeTextForBrowser
*/
"use strict";
var throwIf = require("./throwIf");
var ESCAPE_TYPE_ERR;
if (true) {
ESCAPE_TYPE_ERR =
'The React core has attempted to escape content that is of a ' +
'mysterious type (object etc) Escaping only works on numbers and strings';
}
var ESCAPE_LOOKUP = {
"&": "&",
">": ">",
"<": "<",
"\"": """,
"'": "'",
"/": "/"
};
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
var escapeTextForBrowser = function (text) {
var type = typeof text;
var invalid = type === 'object';
if (true) {
throwIf(invalid, ESCAPE_TYPE_ERR);
}
if (text === '' || invalid) {
return '';
} else {
if (type === 'string') {
return text.replace(/[&><"'\/]/g, escaper);
} else {
return (''+text).replace(/[&><"'\/]/g, escaper);
}
}
};
module.exports = escapeTextForBrowser;
},{"./throwIf":31}],43:[function(require,module,exports){
/**
* 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.
*
* @providesModule flattenChildren
*/
"use strict";
var ReactTextComponent = require("./ReactTextComponent");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var throwIf = require("./throwIf");
/**
* @polyFill Array.isArray
*/
var INVALID_CHILD = 'INVALID_CHILD';
if (true) {
INVALID_CHILD =
'You may not pass a child of that type to a React component. It ' +
'is a common mistake to try to pass a standard browser DOM element ' +
'as a child of a React component.';
}
/**
* If there is only a single child, it still needs a name.
*/
var ONLY_CHILD_NAME = '0';
var flattenChildrenImpl = function(res, children, nameSoFar) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
flattenChildrenImpl(res, children[i], nameSoFar + '[' + i + ']');
}
} else {
var type = typeof children;
var isOnlyChild = nameSoFar === '';
var storageName = isOnlyChild ? ONLY_CHILD_NAME : nameSoFar;
if (children === null || children === undefined || type === 'boolean') {
res[storageName] = null;
} else if (children.mountComponentIntoNode) {
/* We found a component instance */
res[storageName] = children;
} else {
if (type === 'object') {
throwIf(children && children.nodeType === 1, INVALID_CHILD);
for (var key in children) {
if (children.hasOwnProperty(key)) {
flattenChildrenImpl(
res,
children[key],
nameSoFar + '{' + escapeTextForBrowser(key) + '}'
);
}
}
} else if (type === 'string') {
res[storageName] = new ReactTextComponent(children);
} else if (type === 'number') {
res[storageName] = new ReactTextComponent('' + children);
}
}
}
};
/**
* Flattens children that are typically specified as `props.children`.
* @return {!Object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children === null || children === undefined) {
return children;
}
var result = {};
flattenChildrenImpl(result, children, '');
return result;
}
module.exports = flattenChildren;
},{"./ReactTextComponent":65,"./escapeTextForBrowser":42,"./throwIf":31}],45:[function(require,module,exports){
/**
* 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.
*
* @providesModule mergeHelpers
*
* requiresPolyfills: Array.isArray
*/
"use strict";
var keyMirror = require("./keyMirror");
var throwIf = require("./throwIf");
/*
* Maximum number of levels to traverse. Will catch circular structures.
* @const
*/
var MAX_MERGE_DEPTH = 36;
var ERRORS = keyMirror({
MERGE_ARRAY_FAIL: null,
MERGE_CORE_FAILURE: null,
MERGE_TYPE_USAGE_FAILURE: null,
MERGE_DEEP_MAX_LEVELS: null,
MERGE_DEEP_NO_ARR_STRATEGY: null
});
if (true) {
ERRORS = {
MERGE_ARRAY_FAIL:
'Unsupported type passed to a merge function. You may have passed a ' +
'structure that contains an array and the merge function does not know ' +
'how to merge arrays. ',
MERGE_CORE_FAILURE:
'Critical assumptions about the merge functions have been violated. ' +
'This is the fault of the merge functions themselves, not necessarily ' +
'the callers.',
MERGE_TYPE_USAGE_FAILURE:
'Calling merge function with invalid types. You may call merge ' +
'functions (non-array non-terminal) OR (null/undefined) arguments. ' +
'mergeInto functions have the same requirements but with an added ' +
'restriction that the first parameter must not be null/undefined.',
MERGE_DEEP_MAX_LEVELS:
'Maximum deep merge depth exceeded. You may attempting to merge ' +
'circular structures in an unsupported way.',
MERGE_DEEP_NO_ARR_STRATEGY:
'You must provide an array strategy to deep merge functions to ' +
'instruct the deep merge how to resolve merging two arrays.'
};
}
/**
* We won't worry about edge cases like new String('x') or new Boolean(true).
* Functions are considered terminals, and arrays are not.
* @param {*} o The item/object/value to test.
* @return {boolean} true iff the argument is a terminal.
*/
var isTerminal = function(o) {
return typeof o !== 'object' || o === null;
};
var mergeHelpers = {
MAX_MERGE_DEPTH: MAX_MERGE_DEPTH,
isTerminal: isTerminal,
/**
* Converts null/undefined values into empty object.
*
* @param {?Object=} arg Argument to be normalized (nullable optional)
* @return {!Object}
*/
normalizeMergeArg: function(arg) {
return arg === undefined || arg === null ? {} : arg;
},
/**
* If merging Arrays, a merge strategy *must* be supplied. If not, it is
* likely the caller's fault. If this function is ever called with anything
* but `one` and `two` being `Array`s, it is the fault of the merge utilities.
*
* @param {*} one Array to merge into.
* @param {*} two Array to merge from.
*/
checkMergeArrayArgs: function(one, two) {
throwIf(
!Array.isArray(one) || !Array.isArray(two),
ERRORS.MERGE_CORE_FAILURE
);
},
/**
* @param {*} one Object to merge into.
* @param {*} two Object to merge from.
*/
checkMergeObjectArgs: function(one, two) {
mergeHelpers.checkMergeObjectArg(one);
mergeHelpers.checkMergeObjectArg(two);
},
/**
* @param {*} arg
*/
checkMergeObjectArg: function(arg) {
throwIf(isTerminal(arg) || Array.isArray(arg), ERRORS.MERGE_CORE_FAILURE);
},
/**
* Checks that a merge was not given a circular object or an object that had
* too great of depth.
*
* @param {number} Level of recursion to validate against maximum.
*/
checkMergeLevel: function(level) {
throwIf(level >= MAX_MERGE_DEPTH, ERRORS.MERGE_DEEP_MAX_LEVELS);
},
/**
* Checks that a merge was not given a circular object or an object that had
* too great of depth.
*
* @param {number} Level of recursion to validate against maximum.
*/
checkArrayStrategy: function(strategy) {
throwIf(
strategy !== undefined && !(strategy in mergeHelpers.ArrayStrategies),
ERRORS.MERGE_DEEP_NO_ARR_STRATEGY
);
},
/**
* Set of possible behaviors of merge algorithms when encountering two Arrays
* that must be merged together.
* - `clobber`: The left `Array` is ignored.
* - `indexByIndex`: The result is achieved by recursively deep merging at
* each index. (not yet supported.)
*/
ArrayStrategies: keyMirror({
Clobber: true,
IndexByIndex: true
}),
ERRORS: ERRORS
};
module.exports = mergeHelpers;
},{"./keyMirror":11,"./throwIf":31}],47:[function(require,module,exports){
/**
* 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.
*
* @providesModule EventConstants
*/
"use strict";
var keyMirror = require("./keyMirror");
var PropagationPhases = keyMirror({bubbled: null, captured: null});
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topBlur: null,
topChange: null,
topClick: null,
topDOMCharacterDataModified: null,
topDoubleClick: null,
topFocus: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topMouseWheel: null,
topScroll: null,
topSubmit: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
},{"./keyMirror":11}],48:[function(require,module,exports){
/**
* 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.
*
* @providesModule NormalizedEventListener
*/
"use strict";
var EventListener = require("./EventListener");
/**
* @param {?Event} eventParam Event parameter from an attached listener.
* @return {Event} Normalized event object.
* @private
*/
function normalizeEvent(eventParam) {
var normalized = eventParam || window.event;
// In some browsers (OLD FF), setting the target throws an error. A good way
// to tell if setting the target will throw an error, is to check if the event
// has a `target` property. Safari events have a `target` but it's not always
// normalized. Even if a `target` property exists, it's good to only set the
// target property if we realize that a change will actually take place.
var hasTargetProperty = 'target' in normalized;
var eventTarget = normalized.target || normalized.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3)
// @see http://www.quirksmode.org/js/events_properties.html
var textNodeNormalizedTarget =
(eventTarget.nodeType === 3) ? eventTarget.parentNode : eventTarget;
if (!hasTargetProperty || normalized.target !== textNodeNormalizedTarget) {
// Create an object that inherits from the native event so that we can set
// `target` on it. (It is read-only and setting it throws in strict mode).
normalized = Object.create(normalized);
normalized.target = textNodeNormalizedTarget;
}
return normalized;
}
function createNormalizedCallback(cb) {
return function(unfixedNativeEvent) {
cb(normalizeEvent(unfixedNativeEvent));
};
}
var NormalizedEventListener = {
/**
* Listens to bubbled events on a DOM node.
*
* NOTE: The listener will be invoked with a normalized event object.
*
* @param {DOMElement} el DOM element to register listener on.
* @param {string} handlerBaseName Event name, e.g. "click".
* @param {function} cb Callback function.
* @public
*/
listen: function(el, handlerBaseName, cb) {
EventListener.listen(el, handlerBaseName, createNormalizedCallback(cb));
},
/**
* Listens to captured events on a DOM node.
*
* NOTE: The listener will be invoked with a normalized event object.
*
* @param {DOMElement} el DOM element to register listener on.
* @param {string} handlerBaseName Event name, e.g. "click".
* @param {function} cb Callback function.
* @public
*/
capture: function(el, handlerBaseName, cb) {
EventListener.capture(el, handlerBaseName, createNormalizedCallback(cb));
}
};
module.exports = NormalizedEventListener;
},{"./EventListener":66}],49:[function(require,module,exports){
/**
* 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.
*
* @providesModule isEventSupported
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var testNode;
if (ExecutionEnvironment.canUseDOM) {
testNode = document.createElement('div');
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!testNode || (capture && !testNode.addEventListener)) {
return false;
}
var element = document.createElement('div');
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in element;
if (!isSupported) {
element.setAttribute(eventName, '');
isSupported = typeof element[eventName] === 'function';
if (typeof element[eventName] !== 'undefined') {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
element = null;
return isSupported;
}
module.exports = isEventSupported;
},{"./ExecutionEnvironment":14}],52:[function(require,module,exports){
/**
* 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.
*
* @providesModule EventPropagators
*/
"use strict";
var CallbackRegistry = require("./CallbackRegistry");
var EventConstants = require("./EventConstants");
var accumulate = require("./accumulate");
var forEachAccumulated = require("./forEachAccumulated");
var getListener = CallbackRegistry.getListener;
var PropagationPhases = EventConstants.PropagationPhases;
/**
* Injected dependencies:
*/
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var injection = {
InstanceHandle: null,
injectInstanceHandle: function(InjectedInstanceHandle) {
injection.InstanceHandle = InjectedInstanceHandle;
if (true) {
injection.validate();
}
},
validate: function() {
var invalid = !injection.InstanceHandle||
!injection.InstanceHandle.traverseTwoPhase ||
!injection.InstanceHandle.traverseEnterLeave;
if (invalid) {
throw new Error('InstanceHandle not injected before use!');
}
}
};
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, abstractEvent, propagationPhase) {
var registrationName =
abstractEvent.type.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags an `AbstractEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, abstractEvent) {
if (true) {
if (!domID) {
throw new Error('Dispatching id must not be null');
}
injection.validate();
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, abstractEvent, phase);
if (listener) {
abstractEvent._dispatchListeners =
accumulate(abstractEvent._dispatchListeners, listener);
abstractEvent._dispatchIDs = accumulate(abstractEvent._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We can not perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(abstractEvent) {
if (abstractEvent && abstractEvent.type.phasedRegistrationNames) {
injection.InstanceHandle.traverseTwoPhase(
abstractEvent.abstractTargetID,
accumulateDirectionalDispatches,
abstractEvent
);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `abstractTargetID` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, abstractEvent) {
if (abstractEvent && abstractEvent.type.registrationName) {
var listener = getListener(id, abstractEvent.type.registrationName);
if (listener) {
abstractEvent._dispatchListeners =
accumulate(abstractEvent._dispatchListeners, listener);
abstractEvent._dispatchIDs = accumulate(abstractEvent._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `AbstractEvent`, but only for the
* `abstractTargetID`.
* @param {AbstractEvent} abstractEvent
*/
function accumulateDirectDispatchesSingle(abstractEvent) {
if (abstractEvent && abstractEvent.type.registrationName) {
accumulateDispatches(abstractEvent.abstractTargetID, null, abstractEvent);
}
}
function accumulateTwoPhaseDispatches(abstractEvents) {
if (true) {
injection.validate();
}
forEachAccumulated(abstractEvents, accumulateTwoPhaseDispatchesSingle);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
if (true) {
injection.validate();
}
injection.InstanceHandle.traverseEnterLeave(
fromID,
toID,
accumulateDispatches,
leave,
enter
);
}
function accumulateDirectDispatches(abstractEvents) {
if (true) {
injection.validate();
}
forEachAccumulated(abstractEvents, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches,
injection: injection
};
module.exports = EventPropagators;
},{"./CallbackRegistry":54,"./EventConstants":47,"./accumulate":56,"./forEachAccumulated":57}],53:[function(require,module,exports){
/**
* 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.
*
* @providesModule AbstractEvent
*/
"use strict";
var BrowserEnv = require("./BrowserEnv");
var PooledClass = require("./PooledClass");
var TouchEventUtils = require("./TouchEventUtils");
var throwIf = require("./throwIf");
// Only accessed in __DEV__
var CLONE_TYPE_ERR;
if (true) {
CLONE_TYPE_ERR =
'You may only clone instances of AbstractEvent for ' +
'persistent references. Check yourself.';
}
var MAX_POOL_SIZE = 20;
/**
* AbstractEvent copy constructor. @see `PooledClass`. Provides a single place
* to define all cross browser normalization of DOM events. Does not attempt to
* extend a native event, rather creates a completely new object that has a
* reference to the nativeEvent through .nativeEvent member. The property .data
* should hold all data that is extracted from the event in a cross browser
* manner. Application code should use the data field when possible, not the
* unreliable native event.
*/
function AbstractEvent(
abstractEventType,
abstractTargetID, // Allows the abstract target to differ from native.
originatingTopLevelEventType,
nativeEvent,
data) {
this.type = abstractEventType;
this.abstractTargetID = abstractTargetID || '';
this.originatingTopLevelEventType = originatingTopLevelEventType;
this.nativeEvent = nativeEvent;
this.data = data;
// TODO: Deprecate storing target - doesn't always make sense for some types
this.target = nativeEvent && nativeEvent.target;
/**
* As a performance optimization, we tag the existing event with the listeners
* (or listener [singular] if only one). This avoids having to package up an
* abstract event along with the set of listeners into a wrapping "dispatch"
* object. No one should ever read this property except event system and
* plugin/dispatcher code. We also tag the abstract event with a parallel
* ID array. _dispatchListeners[i] is being dispatched to a DOM node at ID
* _dispatchIDs[i]. The lengths should never, ever, ever be different.
*/
this._dispatchListeners = null;
this._dispatchIDs = null;
this.isPropagationStopped = false;
}
/** `PooledClass` looks for this. */
AbstractEvent.poolSize = MAX_POOL_SIZE;
/**
* `PooledClass` looks for `destructor` on each instance it releases. We need to
* ensure that we remove all references to listeners which could trap large
* amounts of memory in their closures.
*/
AbstractEvent.prototype.destructor = function() {
this.target = null;
this._dispatchListeners = null;
this._dispatchIDs = null;
};
/**
* Enhance the `AbstractEvent` class to have pooling abilities. We instruct
* `PooledClass` that our copy constructor accepts five arguments (this is just
* a performance optimization). These objects are instantiated frequently.
*/
PooledClass.addPoolingTo(AbstractEvent, PooledClass.fiveArgumentPooler);
AbstractEvent.prototype.stopPropagation = function() {
this.isPropagationStopped = true;
if (this.nativeEvent.stopPropagation) {
this.nativeEvent.stopPropagation();
}
// IE8 only understands cancelBubble, not stopPropagation().
this.nativeEvent.cancelBubble = true;
};
AbstractEvent.prototype.preventDefault = function() {
AbstractEvent.preventDefaultOnNativeEvent(this.nativeEvent);
};
/**
* Utility function for preventing default in cross browser manner.
*/
AbstractEvent.preventDefaultOnNativeEvent = function(nativeEvent) {
if (nativeEvent.preventDefault) {
nativeEvent.preventDefault();
} else {
nativeEvent.returnValue = false;
}
};
/**
* @param {Element} target The target element.
*/
AbstractEvent.normalizeScrollDataFromTarget = function(target) {
return {
scrollTop: target.scrollTop,
scrollLeft: target.scrollLeft,
clientWidth: target.clientWidth,
clientHeight: target.clientHeight,
scrollHeight: target.scrollHeight,
scrollWidth: target.scrollWidth
};
};
/*
* There are some normalizations that need to happen for various browsers. In
* addition to replacing the general event fixing with a framework such as
* jquery, we need to normalize mouse events here. Code below is mostly borrowed
* from: jScrollPane/script/jquery.mousewheel.js
*/
AbstractEvent.normalizeMouseWheelData = function(nativeEvent) {
var delta = 0;
var deltaX = 0;
var deltaY = 0;
/* traditional scroll wheel data */
if ( nativeEvent.wheelDelta ) { delta = nativeEvent.wheelDelta/120; }
if ( nativeEvent.detail ) { delta = -nativeEvent.detail/3; }
/* Multidimensional scroll (touchpads) with deltas */
deltaY = delta;
/* Gecko based browsers */
if (nativeEvent.axis !== undefined &&
nativeEvent.axis === nativeEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -delta;
}
/* Webkit based browsers */
if (nativeEvent.wheelDeltaY !== undefined ) {
deltaY = nativeEvent.wheelDeltaY/120;
}
if (nativeEvent.wheelDeltaX !== undefined ) {
deltaX = -nativeEvent.wheelDeltaX/120;
}
return { delta: delta, deltaX: deltaX, deltaY: deltaY };
};
/**
* I <3 Quirksmode.org:
* http://www.quirksmode.org/js/events_properties.html
*/
AbstractEvent.isNativeClickEventRightClick = function(nativeEvent) {
return nativeEvent.which ? nativeEvent.which === 3 :
nativeEvent.button ? nativeEvent.button === 2 :
false;
};
AbstractEvent.normalizePointerData = function(nativeEvent) {
return {
globalX: AbstractEvent.eventPageX(nativeEvent),
globalY: AbstractEvent.eventPageY(nativeEvent),
rightMouseButton:
AbstractEvent.isNativeClickEventRightClick(nativeEvent)
};
};
AbstractEvent.normalizeDragEventData =
function(nativeEvent, globalX, globalY, startX, startY) {
return {
globalX: globalX,
globalY: globalY,
startX: startX,
startY: startY
};
};
/**
* Warning: It is possible to move your finger on a touch surface, yet not
* effect the `eventPageX/Y` because the touch had caused a scroll that
* compensated for your movement. To track movements across the page, prevent
* default to avoid scrolling, and control scrolling in javascript.
*/
/**
* Gets the exact position of a touch/mouse event on the page with respect to
* the document body. The only reason why this method is needed instead of using
* `TouchEventUtils.extractSingleTouch` is to support IE8-. Mouse events in all
* browsers except IE8- contain a pageY. IE8 and below require clientY
* computation:
*
* @param {Event} nativeEvent Native event, possibly touch or mouse.
* @return {number} Coordinate with respect to document body.
*/
AbstractEvent.eventPageY = function(nativeEvent) {
var singleTouch = TouchEventUtils.extractSingleTouch(nativeEvent);
if (singleTouch) {
return singleTouch.pageY;
} else if (typeof nativeEvent.pageY !== 'undefined') {
return nativeEvent.pageY;
} else {
return nativeEvent.clientY + BrowserEnv.currentPageScrollTop;
}
};
/**
* @see `AbstractEvent.eventPageY`.
*
* @param {Event} nativeEvent Native event, possibly touch or mouse.
* @return {number} Coordinate with respect to document body.
*/
AbstractEvent.eventPageX = function(nativeEvent) {
var singleTouch = TouchEventUtils.extractSingleTouch(nativeEvent);
if (singleTouch) {
return singleTouch.pageX;
} else if (typeof nativeEvent.pageX !== 'undefined') {
return nativeEvent.pageX;
} else {
return nativeEvent.clientX + BrowserEnv.currentPageScrollLeft;
}
};
/**
* A semantic API around cloning an event for use in another event loop. We
* clear out all dispatched `AbstractEvent`s after each event loop, adding them
* back into the pool. This allows a way to hold onto a reference that won't be
* added back into the pool. Please note that `AbstractEvent.nativeEvent` is
* *not* cloned and you will run into problems in IE if you assume that it will
* be! The moral of that story is to always normalize any data you need into the
* `.data` field. The data field is not cloned either, but there won't be any
* issues related to use of `.data` in a future event cycle so long as no part
* of your application mutates it. We don't clone the private fields because
* your application should never be accessing them.
*
* - TODO: In __DEV__ when "releasing" events, don't put them back into the
* pool. Instead add ES5 getters on all their fields that throw errors so you
* can detect any application that's hanging onto events and reusing them.
* In prod - we can put them back into the pool for reuse.
*/
AbstractEvent.persistentCloneOf = function(abstractEvent) {
if (true) {
throwIf(!(abstractEvent instanceof AbstractEvent), CLONE_TYPE_ERR);
}
return new AbstractEvent(
abstractEvent.type,
abstractEvent.abstractTargetID,
abstractEvent.originatingTopLevelEventType,
abstractEvent.nativeEvent,
abstractEvent.data,
abstractEvent.target
);
};
module.exports = AbstractEvent;
},{"./BrowserEnv":46,"./PooledClass":37,"./TouchEventUtils":67,"./throwIf":31}],55:[function(require,module,exports){
/**
* 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.
*
* @providesModule EventPluginUtils
*/
"use strict";
var EventConstants = require("./EventConstants");
var AbstractEvent = require("./AbstractEvent");
var invariant = require("./invariant");
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp ||
topLevelType === topLevelTypes.topTouchEnd ||
topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove ||
topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown ||
topLevelType === topLevelTypes.topTouchStart;
}
function storePageCoordsIn(obj, nativeEvent) {
var pageX = AbstractEvent.eventPageX(nativeEvent);
var pageY = AbstractEvent.eventPageY(nativeEvent);
obj.pageX = pageX;
obj.pageY = pageY;
}
function eventDistance(coords, nativeEvent) {
var pageX = AbstractEvent.eventPageX(nativeEvent);
var pageY = AbstractEvent.eventPageY(nativeEvent);
return Math.pow(
Math.pow(pageX - coords.pageX, 2) + Math.pow(pageY - coords.pageY, 2),
0.5
);
}
var validateEventDispatches;
if (true) {
validateEventDispatches = function(abstractEvent) {
var dispatchListeners = abstractEvent._dispatchListeners;
var dispatchIDs = abstractEvent._dispatchIDs;
var listenersIsArr = Array.isArray(dispatchListeners);
var idsIsArr = Array.isArray(dispatchIDs);
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
var listenersLen = listenersIsArr ?
dispatchListeners.length :
dispatchListeners ? 1 : 0;
invariant(
idsIsArr === listenersIsArr && IDsLen === listenersLen,
'EventPluginUtils: Invalid `abstractEvent`.'
);
};
}
/**
* Invokes `cb(abstractEvent, listener, id)`. Avoids using call if no scope is
* provided. The `(listener,id)` pair effectively forms the "dispatch" but are
* kept separate to conserve memory.
*/
function forEachEventDispatch(abstractEvent, cb) {
var dispatchListeners = abstractEvent._dispatchListeners;
var dispatchIDs = abstractEvent._dispatchIDs;
if (true) {
validateEventDispatches(abstractEvent);
}
if (Array.isArray(dispatchListeners)) {
var i;
for (
i = 0;
i < dispatchListeners.length && !abstractEvent.isPropagationStopped;
i++) {
// Listeners and IDs are two parallel arrays that are always in sync.
cb(abstractEvent, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
cb(abstractEvent, dispatchListeners, dispatchIDs);
}
}
/**
* Default implementation of PluginModule.executeDispatch().
* @param {AbstractEvent} AbstractEvent to handle
* @param {function} Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(abstractEvent, listener, domID) {
listener(abstractEvent, domID);
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(abstractEvent, executeDispatch) {
forEachEventDispatch(abstractEvent, executeDispatch);
abstractEvent._dispatchListeners = null;
abstractEvent._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @returns id of the first dispatch execution who's listener returns true, or
* null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrue(abstractEvent) {
var dispatchListeners = abstractEvent._dispatchListeners;
var dispatchIDs = abstractEvent._dispatchIDs;
if (true) {
validateEventDispatches(abstractEvent);
}
if (Array.isArray(dispatchListeners)) {
var i;
for (
i = 0;
i < dispatchListeners.length && !abstractEvent.isPropagationStopped;
i++) {
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](abstractEvent, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(abstractEvent, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @returns The return value of executing the single dispatch.
*/
function executeDirectDispatch(abstractEvent) {
if (true) {
validateEventDispatches(abstractEvent);
}
var dispatchListener = abstractEvent._dispatchListeners;
var dispatchID = abstractEvent._dispatchIDs;
invariant(
!Array.isArray(dispatchListener),
'executeDirectDispatch(...): Invalid `abstractEvent`.'
);
var res = dispatchListener ?
dispatchListener(abstractEvent, dispatchID) :
null;
abstractEvent._dispatchListeners = null;
abstractEvent._dispatchIDs = null;
return res;
}
/**
* @param {AbstractEvent} abstractEvent
* @returns {bool} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(abstractEvent) {
return !!abstractEvent._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
storePageCoordsIn: storePageCoordsIn,
eventDistance: eventDistance,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
executeDirectDispatch: executeDirectDispatch,
hasDispatches: hasDispatches,
executeDispatch: executeDispatch
};
module.exports = EventPluginUtils;
},{"./EventConstants":47,"./AbstractEvent":53,"./invariant":10}],56:[function(require,module,exports){
/**
* 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.
*
* @providesModule accumulate
*/
"use strict";
var throwIf = require("./throwIf");
var INVALID_ARGS = 'INVALID_ACCUM_ARGS';
if (true) {
INVALID_ARGS =
'accumulate requires non empty (non-null, defined) next ' +
'values. All arrays accumulated must not contain any empty items.';
}
/**
* Accumulates items that must never be empty, into a result in a manner that
* conserves memory - avoiding allocation of arrays until they are needed. The
* accumulation may start and/or end up being a single element or an array
* depending on the total count (if greater than one, an array is allocated).
* Handles most common case first (starting with an empty current value and
* acquiring one).
* @returns {Accumulation} An accumulation which is either a single item or an
* Array of items.
*/
function accumulate(cur, next) {
var curValIsEmpty = cur == null; // Will test for emptiness (null/undef)
var nextValIsEmpty = next === null;
if (true) {
throwIf(nextValIsEmpty, INVALID_ARGS);
}
if (nextValIsEmpty) {
return cur;
} else {
if (curValIsEmpty) {
return next;
} else {
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var curIsArray = Array.isArray(cur);
var nextIsArray = Array.isArray(next);
if (curIsArray) {
return cur.concat(next);
} else {
if (nextIsArray) {
return [cur].concat(next);
} else {
return [cur, next];
}
}
}
}
}
module.exports = accumulate;
},{"./throwIf":31}],58:[function(require,module,exports){
/**
* 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.
*
* @providesModule copyProperties
*/
/**
* Copy properties from one or more objects (up to 5) into the first object.
* This is a shallow copy. It mutates the first object and also returns it.
*
* NOTE: `arguments` has a very significant performance penalty, which is why
* we don't support unlimited arguments.
*/
function copyProperties(obj, a, b, c, d, e, f) {
obj = obj || {};
if (true) {
if (f) {
throw new Error('Too many arguments passed to copyProperties');
}
}
var args = [a, b, c, d, e];
var ii = 0, v;
while (args[ii]) {
v = args[ii++];
for (var k in v) {
obj[k] = v[k];
}
// IE ignores toString in object iteration.. See:
// webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html
if (v.hasOwnProperty && v.hasOwnProperty('toString') &&
(typeof v.toString != 'undefined') && (obj.toString !== v.toString)) {
obj.toString = v.toString;
}
}
return obj;
}
module.exports = copyProperties;
},{}],60:[function(require,module,exports){
/**
* 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.
*
* @providesModule hyphenate
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],61:[function(require,module,exports){
/**
* 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.
*
* @providesModule memoizeStringOnly
* @typechecks
*/
"use strict";
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function(string) {
if (cache.hasOwnProperty(string)) {
return cache[string];
} else {
return cache[string] = callback.call(this, string);
}
};
}
module.exports = memoizeStringOnly;
},{}],63:[function(require,module,exports){
/**
* 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.
*
* @providesModule insertNodeAt
*/
"use strict";
/**
* Inserts `node` at a particular child index. Other nodes move to make room.
* @param {!Element} root The parent root node to insert into.
* @param {!node} node The node to insert.
* @param {!number} atIndex The index in `root` that `node` should exist at.
*/
function insertNodeAt(root, node, atIndex) {
var childNodes = root.childNodes;
// Remove from parent so that if node is already child of root,
// `childNodes[atIndex]` already takes into account the removal.
var curAtIndex = root.childNodes[atIndex];
if (curAtIndex === node) {
return node;
}
if (node.parentNode) {
node.parentNode.removeChild(node);
}
if (atIndex >= childNodes.length) {
root.appendChild(node);
} else {
root.insertBefore(node, childNodes[atIndex]);
}
return node;
}
module.exports = insertNodeAt;
},{}],66:[function(require,module,exports){
/**
* 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.
*
* @providesModule EventListener
*/
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listens to bubbled events on a DOM node.
*
* @param {Element} el DOM element to register listener on.
* @param {string} handlerBaseName 'click'/'mouseover'
* @param {Function!} cb Callback function
*/
listen: function(el, handlerBaseName, cb) {
if (el.addEventListener) {
el.addEventListener(handlerBaseName, cb, false);
} else if (el.attachEvent) {
el.attachEvent('on' + handlerBaseName, cb);
}
},
/**
* Listens to captured events on a DOM node.
*
* @see `EventListener.listen` for params.
* @throws Exception if addEventListener is not supported.
*/
capture: function(el, handlerBaseName, cb) {
if (!el.addEventListener) {
console.error(
'You are attempting to use addEventlistener ' +
'in a browser that does not support it support it.' +
'This likely means that you will not receive events that ' +
'your application relies on (such as scroll).');
return;
} else {
el.addEventListener(handlerBaseName, cb, true);
}
}
};
module.exports = EventListener;
},{}],67:[function(require,module,exports){
/**
* 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.
*
* @providesModule TouchEventUtils
*/
var TouchEventUtils = {
/**
* Utility function for common case of extracting out the primary touch from a
* touch event.
* - `touchEnd` events usually do not have the `touches` property.
* http://stackoverflow.com/questions/3666929/
* mobile-sarai-touchend-event-not-firing-when-last-touch-is-removed
*
* @param {Event} nativeEvent Native event that may or may not be a touch.
* @return {TouchesObject?} an object with pageX and pageY or null.
*/
extractSingleTouch: function(nativeEvent) {
var touches = nativeEvent.touches;
var changedTouches = nativeEvent.changedTouches;
var hasTouches = touches && touches.length > 0;
var hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches ? changedTouches[0] :
hasTouches ? touches[0] :
nativeEvent;
}
};
module.exports = TouchEventUtils;
},{}],59:[function(require,module,exports){
/**
* 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.
*
* @providesModule dangerousStyleValue
* @typechecks
*/
"use strict";
var CSSProperty = require("./CSSProperty");
/**
* Convert a value into the proper css writable value. The `styleName` name
* name should be logical (no hyphens), as specified in `CSSProperty.isNumber`.
*
* @param {string} styleName CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(styleName, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
if (value === null || value === false || value === true || value === '') {
return '';
}
if (isNaN(value)) {
return !value ? '' : '' + value;
}
return CSSProperty.isNumber[styleName] ? '' + value : (value + 'px');
}
module.exports = dangerousStyleValue;
},{"./CSSProperty":68}],62:[function(require,module,exports){
/**
* 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.
*
* @providesModule Danger
*/
"use strict";
var ExecutionEnvironment = require("./ExecutionEnvironment");
var throwIf = require("./throwIf");
var DOM_UNSUPPORTED;
var NO_MARKUP_PARENT;
var NO_MULTI_MARKUP;
if (true) {
DOM_UNSUPPORTED =
'You may not insert markup into the document while you are in a worker ' +
'thread. It\'s not you, it\'s me. This is likely the fault of the ' +
'framework. Please report this immediately.';
NO_MARKUP_PARENT =
'You have attempted to inject markup without a suitable parent. This is ' +
'likely the fault of the framework - please report immediately.';
NO_MULTI_MARKUP =
'The framework has attempted to either insert zero or multiple markup ' +
'roots into a single location when it should not. This is a serious ' +
'error - a fault of the framework - please report immediately.';
}
var validateMarkupParams;
if (true) {
validateMarkupParams = function(parentNode, markup) {
throwIf(!ExecutionEnvironment.canUseDOM, DOM_UNSUPPORTED);
throwIf(!parentNode || !parentNode.tagName, NO_MARKUP_PARENT);
throwIf(!markup, NO_MULTI_MARKUP);
};
}
var dummies = {};
function getParentDummy(parent) {
var parentTag = parent.tagName;
return dummies[parentTag] ||
(dummies[parentTag] = document.createElement(parentTag));
}
/**
* Inserts node after 'after'. If 'after' is null, inserts it after nothing,
* which is inserting it at the beginning.
*
* @param {Element} elem Parent element.
* @param {Element} insert Element to insert.
* @param {Element} after Element to insert after.
* @returns {Element} Element that was inserted.
*/
function insertNodeAfterNode(elem, insert, after) {
if (true) {
throwIf(!ExecutionEnvironment.canUseDOM, DOM_UNSUPPORTED);
}
if (after) {
if (after.nextSibling) {
return elem.insertBefore(insert, after.nextSibling);
} else {
return elem.appendChild(insert);
}
} else {
return elem.insertBefore(insert, elem.firstChild);
}
}
/**
* Slow: Should only be used when it is known there are a few (or one) element
* in the node list.
* @param {Element} parentRootDomNode Parent element.
* @param {HTMLCollection} htmlCollection HTMLCollection to insert.
* @param {Element} after Element to insert the node list after.
*/
function inefficientlyInsertHTMLCollectionAfter(
parentRootDomNode,
htmlCollection,
after) {
if (true) {
throwIf(!ExecutionEnvironment.canUseDOM, DOM_UNSUPPORTED);
}
var ret;
var originalLength = htmlCollection.length;
// Access htmlCollection[0] because htmlCollection shrinks as we remove items.
// `insertNodeAfterNode` will remove items from the htmlCollection.
for (var i = 0; i < originalLength; i++) {
ret =
insertNodeAfterNode(parentRootDomNode, htmlCollection[0], ret || after);
}
}
/**
* Super-dangerously inserts markup into existing DOM structure. Seriously, you
* don't want to use this module unless you are building a framework. This
* requires that the markup that you are inserting represents the root of a
* tree. We do not support the case where there `markup` represents several
* roots.
*
* @param {Element} parentNode Parent DOM element.
* @param {string} markup Markup to dangerously insert.
* @param {number} index Position to insert markup at.
*/
function dangerouslyInsertMarkupAt(parentNode, markup, index) {
if (true) {
validateMarkupParams(parentNode, markup);
}
var parentDummy = getParentDummy(parentNode);
parentDummy.innerHTML = markup;
var htmlCollection = parentDummy.childNodes;
var afterNode = index ? parentNode.childNodes[index - 1] : null;
inefficientlyInsertHTMLCollectionAfter(parentNode, htmlCollection, afterNode);
}
/**
* Replaces a node with a string of markup at its current position within its
* parent. `childNode` must be in the document (or at least within a parent
* node). The string of markup must represent a tree of markup with a single
* root.
*
* @param {Element} childNode Child node to replace.
* @param {string} markup Markup to dangerously replace child with.
*/
function dangerouslyReplaceNodeWithMarkup(childNode, markup) {
var parentNode = childNode.parentNode;
if (true) {
validateMarkupParams(parentNode, markup);
}
var parentDummy = getParentDummy(parentNode);
parentDummy.innerHTML = markup;
var htmlCollection = parentDummy.childNodes;
if (true) {
throwIf(htmlCollection.length !== 1, NO_MULTI_MARKUP);
}
parentNode.replaceChild(htmlCollection[0], childNode);
}
var Danger = {
dangerouslyInsertMarkupAt: dangerouslyInsertMarkupAt,
dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup
};
module.exports = Danger;
},{"./ExecutionEnvironment":14,"./throwIf":31}],64:[function(require,module,exports){
/**
* 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.
*
* @providesModule DOMProperty
* @typechecks
*/
/*jslint bitwise: true */
"use strict";
var invariant = require("./invariant");
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
/**
* Checks whether a property name is a standard property.
* @type {Object}
*/
isStandardName: {},
/**
* Mapping from normalized names to attribute names that differ. Attribute
* names are used when rendering markup or with `*Attribute()`.
* @type {Object}
*/
getAttributeName: {},
/**
* Mapping from normalized names to properties on DOM node instances.
* (This includes properties that mutate due to external factors.)
* @type {Object}
*/
getPropertyName: {},
/**
* Mapping from normalized names to mutation methods. This will only exist if
* mutation cannot be set simply by the property or `setAttribute()`.
* @type {Object}
*/
getMutationMethod: {},
/**
* Whether the property must be accessed and mutated as an object property.
* @type {Object}
*/
mustUseAttribute: {},
/**
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* @type {Object}
*/
mustUseProperty: {},
/**
* Whether the property should be removed when set to a falsey value.
* @type {Object}
*/
hasBooleanValue: {},
/**
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. We must ensure that
* the value is only set if it has changed.
* @type {Object}
*/
hasSideEffects: {},
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
)
};
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
var MustUseAttribute = 0x1;
var MustUseProperty = 0x2;
var HasBooleanValue = 0x4;
var HasSideEffects = 0x8;
var Properties = {
/**
* Standard Properties
*/
accept: null,
action: null,
ajaxify: MustUseAttribute,
allowFullScreen: MustUseAttribute | HasBooleanValue,
alt: null,
autoComplete: null,
autoplay: HasBooleanValue,
cellPadding: null,
cellSpacing: null,
checked: MustUseProperty | HasBooleanValue,
className: MustUseProperty,
colSpan: null,
contentEditable: null,
controls: MustUseProperty | HasBooleanValue,
data: null, // For `<object />` acts as `src`.
dir: null,
disabled: MustUseProperty | HasBooleanValue,
enctype: null,
height: null,
href: null,
htmlFor: null,
method: null,
multiple: MustUseProperty | HasBooleanValue,
name: null,
poster: null,
preload: null,
placeholder: null,
rel: null,
required: HasBooleanValue,
role: MustUseAttribute,
scrollLeft: MustUseProperty,
scrollTop: MustUseProperty,
selected: MustUseProperty | HasBooleanValue,
spellCheck: null,
src: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
value: MustUseProperty | HasSideEffects,
width: null,
wmode: MustUseAttribute,
/**
* SVG Properties
*/
cx: MustUseProperty,
cy: MustUseProperty,
d: MustUseProperty,
fill: MustUseProperty,
fx: MustUseProperty,
fy: MustUseProperty,
points: MustUseProperty,
r: MustUseProperty,
stroke: MustUseProperty,
strokeLinecap: MustUseProperty,
strokeWidth: MustUseProperty,
transform: MustUseProperty,
x: MustUseProperty,
x1: MustUseProperty,
x2: MustUseProperty,
version: MustUseProperty,
viewBox: MustUseProperty,
y: MustUseProperty,
y1: MustUseProperty,
y2: MustUseProperty,
spreadMethod: MustUseProperty,
offset: MustUseProperty,
stopColor: MustUseProperty,
stopOpacity: MustUseProperty,
gradientUnits: MustUseProperty,
gradientTransform: MustUseProperty
};
/**
* Attribute names not specified use the **lowercase** normalized name.
*/
var DOMAttributeNames = {
className: 'class',
htmlFor: 'for',
strokeLinecap: 'stroke-linecap',
strokeWidth: 'stroke-width',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity'
};
/**
* Property names not specified use the normalized name.
*/
var DOMPropertyNames = {
autoComplete: 'autocomplete',
spellCheck: 'spellcheck'
};
/**
* Properties that require special mutation methods.
*/
var DOMMutationMethods = {
/**
* Setting `className` to null may cause it to be set to the string "null".
*
* @param {DOMElement} node
* @param {*} value
*/
className: function(node, value) {
node.className = value || '';
}
};
for (var propName in Properties) {
DOMProperty.isStandardName[propName] = true;
DOMProperty.getAttributeName[propName] =
DOMAttributeNames[propName] || propName.toLowerCase();
DOMProperty.getPropertyName[propName] =
DOMPropertyNames[propName] || propName;
var mutationMethod = DOMMutationMethods[propName];
if (mutationMethod) {
DOMProperty.getMutationMethod[propName] = mutationMethod;
}
var propConfig = Properties[propName];
DOMProperty.mustUseAttribute[propName] = propConfig & MustUseAttribute;
DOMProperty.mustUseProperty[propName] = propConfig & MustUseProperty;
DOMProperty.hasBooleanValue[propName] = propConfig & HasBooleanValue;
DOMProperty.hasSideEffects[propName] = propConfig & HasSideEffects;
invariant(
!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName],
'DOMProperty: Cannot use require using both attribute and property: %s',
propName
);
invariant(
DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName],
'DOMProperty: Properties that have side effects must use property: %s',
propName
);
}
module.exports = DOMProperty;
},{"./invariant":10}],65:[function(require,module,exports){
/**
* 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.
*
* @providesModule ReactTextComponent
* @typechecks
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var escapeTextForBrowser = require("./escapeTextForBrowser");
var mixInto = require("./mixInto");
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings in elements so that they can undergo
* the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactTextComponent
* @extends ReactComponent
* @internal
*/
var ReactTextComponent = function(initialText) {
this.construct({text: initialText});
};
mixInto(ReactTextComponent, ReactComponent.Mixin);
mixInto(ReactTextComponent, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {string} rootID DOM ID of the root node.
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(rootID) {
ReactComponent.Mixin.mountComponent.call(this, rootID);
return (
'<span id="' + rootID + '">' +
escapeTextForBrowser(this.props.text) +
'</span>'
);
},
/**
* Updates this component by updating the text content.
*
* @param {object} nextProps Contains the next text content.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveProps: function(nextProps, transaction) {
if (nextProps.text !== this.props.text) {
this.props.text = nextProps.text;
ReactComponent.DOMIDOperations.updateTextContentByID(
this._rootNodeID,
nextProps.text
);
}
}
});
module.exports = ReactTextComponent;
},{"./ReactComponent":3,"./escapeTextForBrowser":42,"./mixInto":13}],68:[function(require,module,exports){
/**
* 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.
*
* @providesModule CSSProperty
*/
"use strict";
/**
* CSS properties for which we do not append "px".
*/
var isNumber = {
fillOpacity: true,
fontWeight: true,
opacity: true,
orphans: true,
textDecoration: true,
zIndex: true,
zoom: true
};
var CSSProperty = {
isNumber: isNumber
};
module.exports = CSSProperty;
},{}]},{},[1])(1)
});
; |
src/components/Share/Share.js | chengjianhua/book-share | /**
* Created by cjh95414 on 2016/5/3.
*/
import React, { Component } from 'react';
import { withRouter } from 'react-router';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import TextField from 'material-ui/TextField';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import ActionSearch from 'material-ui/svg-icons/action/search';
import Dialog from 'material-ui/Dialog';
import Divider from 'material-ui/Divider';
import Avatar from 'material-ui/Avatar';
import { ListItem } from 'material-ui/List';
import { darkBlack, lightBlack } from 'material-ui/styles/colors'; // eslint-disable-line
import * as actions from 'actions/Share';
import SelectableList from 'components/common/SelectableList';
import s from './Share.scss';
function getStyles() {
return {
smallIcon: { width: 36, height: 36 },
small: { width: 72, height: 72, padding: 16 },
dialogContent: { width: '100%', maxWidth: 'none' },
avatar: { borderRadius: 0, height: '55px', backgroundRepeat: 'no-repeat', backgroundPosition: 'center' },
};
}
class Share extends Component {
state = {
openSearchDialog: false,
openAlertDialog: false,
bookTitle: '',
shareTitle: '',
shareContent: '',
detail: null,
selectedIndex: 0,
};
handleOpenSearchDialog = () => {
// the text which user inputted
const { actions: { searchFromDouban } } = this.props;
const { bookTitle } = this.state;
searchFromDouban(bookTitle)
.then(() => {
this.setState({
openSearchDialog: true,
});
});
};
// just be used to set the state for close the dialog
handleCloseDialog = () => {
this.setState({
openSearchDialog: false,
});
};
handleCancelDialog = () => {
this.handleCloseDialog();
this.setState({
bookSearchResult: [],
});
};
handleBookTitleChange = (event, value) => {
this.setState({
bookTitle: value,
});
};
handleShareTitleChange = (event, value) => {
this.setState({
shareTitle: value,
});
};
handleShareContentChange = (event, value) => {
this.setState({
shareContent: value,
});
};
handleSelectBook = (index) => {
this.setState({
selectedIndex: index,
});
};
handleConfirmDialog = () => {
const { selectedIndex } = this.state;
const { bookSearchResult } = this.props;
const detail = bookSearchResult.get(selectedIndex);
this.setState({
detail,
bookTitle: detail.get('title'),
});
this.handleCloseDialog();
};
handleSubmitForm = (event) => {
event.preventDefault();
// the data will be posted to server
const { actions: { create } } = this.props;
const { detail, bookTitle, shareTitle, shareContent } = this.state;
const data = {
detail,
bookTitle,
shareTitle,
shareContent,
};
// interact with the server and post the "share" to server then handle returned result.
create(data)
.then(() => {
this.handleCloseDialog();
});
};
// an alert dialog that remind user who have post submit successfully.
handleOpenAlertDialog = () => {
this.setState({
openAlertDialog: true,
});
// 2000ms later, the view switched to homepage.
setTimeout(() => {
this.props.router.push('/');
}, 2000);
};
render() {
const { bookSearchResult } = this.props;
const { bookTitle, shareTitle, shareContent, openSearchDialog, openAlertDialog } = this.state;
const styles = getStyles();
const dialogActions = [
<FlatButton
label="取消"
onTouchTap={this.handleCancelDialog}
/>,
<FlatButton
secondary
keyboardFocused
label="确认"
onTouchTap={this.handleConfirmDialog}
/>,
];
const listItems = bookSearchResult.map((book, index, array) => [
<ListItem
key={book.get('title') + book.get('author')}
value={index}
leftAvatar={<Avatar style={styles.avatar} src={book.get('image')} />}
primaryText={book.get('title')}
secondaryText={
<p>
<span style={{ color: darkBlack }}>{book.get('author')}</span>
<br />
{book.get('publisher')}
</p>
}
secondaryTextLines={2}
/>,
index + 1 < array.length && <Divider inset />,
]).toArray();
return (
<div className={s.root}>
<form onSubmit={this.handleSubmitForm} method="post" action="/manage/share/add">
<div className={s.bookInputContainer}>
<TextField
fullWidth
key="bookTitle"
value={bookTitle}
hintText="告诉大家您想分享的书籍~"
floatingLabelText="书籍名称"
onChange={this.handleBookTitleChange}
/>
<div className={s.iconSearch}>
<IconButton
iconStyle={styles.smallIcon}
style={styles.small}
onTouchTap={this.handleOpenSearchDialog}
>
<ActionSearch />
</IconButton>
</div>
</div>
<TextField
fullWidth
key="shareTitle"
hintText="给您的分享一个具有极大吸引力的标题吧~"
floatingLabelText="分享标题"
value={shareTitle}
onChange={this.handleShareTitleChange}
/>
<TextField
fullWidth
multiLine
key="shareContent"
hintText="将这本令你禁不住分享的书籍中您觉得的很棒的推荐理由告诉大家吧……"
style={{ marginTop: '1rem' }}
value={shareContent}
onChange={this.handleShareContentChange}
/>
<div className={s.fixBottom}>
<RaisedButton
primary
label="分享"
type="submit"
style={{ width: '100%' }}
/>
</div>
</form>
<Dialog
modal
key="searchResult"
title="书籍搜索结果"
contentStyle={styles.dialogContent}
actions={dialogActions}
open={openSearchDialog}
onRequestClose={this.handleCancelDialog}
autoScrollBodyContent
>
<SelectableList onSelected={this.handleSelectBook}>
{listItems}
</SelectableList>
</Dialog>
<Dialog
modal
key="submitResult"
open={openAlertDialog}
>
分享成功
</Dialog>
</div>
);
}
}
export default connect(({ share }) => ({
bookSearchResult: share.get('bookSearchResult'),
}), dispatch => ({
actions: bindActionCreators(Object.assign({}, actions), dispatch),
}))(withStyles(s)(withRouter(Share)));
|
src/oneTwoThreeApp/components/Three.js | yosuzuk/react-playground | import React from 'react';
const Three = ({ children }) => (
<div>Three! {children}</div>
);
export default Three;
|
docs/src/routes/error/ErrorPage.js | bmatthews/haze-lea | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ErrorPage.css';
class ErrorPage extends React.Component {
static propTypes = {
error: PropTypes.shape({
name: PropTypes.string.isRequired,
message: PropTypes.string.isRequired,
stack: PropTypes.string.isRequired,
}),
};
static defaultProps = {
error: null,
};
render() {
if (__DEV__ && this.props.error) {
return (
<div>
<h1>
{this.props.error.name}
</h1>
<pre>
{this.props.error.stack}
</pre>
</div>
);
}
return (
<div>
<h1>Error</h1>
<p>Sorry, a critical error occurred on this page.</p>
</div>
);
}
}
export { ErrorPage as ErrorPageWithoutStyle };
export default withStyles(s)(ErrorPage);
|
ajax/libs/F2/1.3.3/f2.js | agraebe/cdnjs | ;(function(exports) {
if (exports.F2 && !exports.F2_TESTING_MODE) {
return;
}
/*!
JSON.org requires the following notice to accompany json2:
Copyright (c) 2002 JSON.org
http://json.org
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
/*
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
/*!
* jQuery JavaScript Library v1.8.3
* The jQuery Foundation and other contributors require the following notice to accompany jQuery:
*
* Copyright (c) 2013 jQuery Foundation and other contributors
*
* http://jquery.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/*! =========================================================
* bootstrap-modal.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#modals
* =========================================================
* Twitter, Inc. require the following notice to accompany Bootstrap:
*
* Copyright (c) 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work
* except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing permissions and limitations under the License.
*
* ========================================================= */
!function ($) {
"use strict"; // jshint ;_;
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function (element, options) {
this.options = options
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
this.options.remote && this.$element.find('.modal-body').load(this.options.remote)
}
Modal.prototype = {
constructor: Modal
, toggle: function () {
return this[!this.isShown ? 'show' : 'hide']()
}
, show: function () {
var that = this
, e = $.Event('show')
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(document.body) //don't move modals dom position
}
that.$element
.show()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
transition ?
that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) :
that.$element.focus().trigger('shown')
})
}
, hide: function (e) {
e && e.preventDefault()
var that = this
e = $.Event('hide')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal()
}
, enforceFocus: function () {
var that = this
$(document).on('focusin.modal', function (e) {
if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
that.$element.focus()
}
})
}
, escape: function () {
var that = this
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.modal', function ( e ) {
e.which == 27 && that.hide()
})
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
}
, hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end)
that.hideModal()
}, 500)
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout)
that.hideModal()
})
}
, hideModal: function (that) {
this.$element
.hide()
.trigger('hidden')
this.backdrop()
}
, removeBackdrop: function () {
this.$backdrop.remove()
this.$backdrop = null
}
, backdrop: function (callback) {
var that = this
, animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
this.$backdrop.click(
this.options.backdrop == 'static' ?
$.proxy(this.$element[0].focus, this.$element[0])
: $.proxy(this.hide, this)
)
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
doAnimate ?
this.$backdrop.one($.support.transition.end, callback) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade')?
this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) :
this.removeBackdrop()
} else if (callback) {
callback()
}
}
}
/* MODAL PLUGIN DEFINITION
* ======================= */
var old = $.fn.modal
$.fn.modal = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
$.fn.modal.defaults = {
backdrop: true
, keyboard: true
, show: true
}
$.fn.modal.Constructor = Modal
/* MODAL NO CONFLICT
* ================= */
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
/* MODAL DATA-API
* ============== */
$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
, href = $this.attr('href')
, $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
, option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option)
.one('hide', function () {
$this.focus()
})
})
}(window.jQuery);
/*!
* This file creates $ and jQuery variables within the F2 closure scope
*/
var $, jQuery = $ = window.jQuery.noConflict(true);
/*!
* Hij1nx requires the following notice to accompany EventEmitter:
*
* Copyright (c) 2011 hij1nx
*
* http://www.twitter.com/hij1nx
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the 'Software'), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
!function(exports, undefined) {
var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
var defaultMaxListeners = 10;
function init() {
this._events = new Object;
}
function configure(conf) {
if (conf) {
conf.delimiter && (this.delimiter = conf.delimiter);
conf.wildcard && (this.wildcard = conf.wildcard);
if (this.wildcard) {
this.listenerTree = new Object;
}
}
}
function EventEmitter(conf) {
this._events = new Object;
configure.call(this, conf);
}
//
// Attention, function return type now is array, always !
// It has zero elements if no any matches found and one or more
// elements (leafs) if there are matches
//
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
typeLength = type.length, currentType = type[i], nextType = type[i+1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
handlers && handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
handlers && handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
}
}
return listeners;
} else if(currentType === '**') {
endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
if(endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if(branch === '*' || branch === '**') {
if(tree[branch]._listeners && !endReached) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
} else if(branch === nextType) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i+1);
}
xxTree = tree['**'];
if(xxTree) {
if(i < typeLength) {
if(xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for(branch in xxTree) {
if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if(branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i+2);
} else if(branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i+1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
}
}
}
} else if(xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if(xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
function growListenerTree(type, listener) {
type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
//
// Looks for two consecutive '**', if so, don't add the event at all.
//
for(var i = 0, len = type.length; i+1 < len; i++) {
if(type[i] === '**' && type[i+1] === '**') {
return;
}
}
var tree = this.listenerTree;
var name = type.shift();
while (name) {
if (!tree[name]) {
tree[name] = new Object;
}
tree = tree[name];
if (type.length === 0) {
if (!tree._listeners) {
tree._listeners = listener;
}
else if(typeof tree._listeners === 'function') {
tree._listeners = [tree._listeners, listener];
}
else if (isArray(tree._listeners)) {
tree._listeners.push(listener);
if (!tree._listeners.warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && tree._listeners.length > m) {
tree._listeners.warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
tree._listeners.length);
console.trace();
}
}
}
return true;
}
name = type.shift();
}
return true;
};
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.delimiter = '.';
EventEmitter.prototype.setMaxListeners = function(n) {
this._events || init.call(this);
this._events.maxListeners = n;
};
EventEmitter.prototype.event = '';
EventEmitter.prototype.once = function(event, fn) {
this.many(event, 1, fn);
return this;
};
EventEmitter.prototype.many = function(event, ttl, fn) {
var self = this;
if (typeof fn !== 'function') {
throw new Error('many only accepts instances of Function');
}
function listener() {
if (--ttl === 0) {
self.off(event, listener);
}
fn.apply(this, arguments);
};
listener._origin = fn;
this.on(event, listener);
return self;
};
EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if (type === 'newListener') {
if (!this._events.newListener) { return false; }
}
// Loop through the *_all* functions and invoke them.
if (this._all) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
for (i = 0, l = this._all.length; i < l; i++) {
this.event = type;
this._all[i].apply(this, args);
}
}
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._all &&
!this._events.error &&
!(this.wildcard && this.listenerTree.error)) {
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
var handler;
if(this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
}
else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
if (arguments.length === 1) {
handler.call(this);
}
else if (arguments.length > 1)
switch (arguments.length) {
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
handler.apply(this, args);
}
return true;
}
else if (handler) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
this.event = type;
listeners[i].apply(this, args);
}
return (listeners.length > 0) || this._all;
}
else {
return this._all;
}
};
EventEmitter.prototype.on = function(type, listener) {
if (typeof type === 'function') {
this.onAny(type);
return this;
}
if (typeof listener !== 'function') {
throw new Error('on only accepts instances of Function');
}
this._events || init.call(this);
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if(this.wildcard) {
growListenerTree.call(this, type, listener);
return this;
}
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
}
else if(typeof this._events[type] === 'function') {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
else if (isArray(this._events[type])) {
// If we've already got an array, just append.
this._events[type].push(listener);
// Check for listener leak
if (!this._events[type].warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.onAny = function(fn) {
if(!this._all) {
this._all = [];
}
if (typeof fn !== 'function') {
throw new Error('onAny only accepts instances of Function');
}
// Add the function to the event listener collection.
this._all.push(fn);
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function(type, listener) {
if (typeof listener !== 'function') {
throw new Error('removeListener only takes instances of Function');
}
var handlers,leafs=[];
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
}
else {
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events[type]) return this;
handlers = this._events[type];
leafs.push({_listeners:handlers});
}
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
handlers = leaf._listeners;
if (isArray(handlers)) {
var position = -1;
for (var i = 0, length = handlers.length; i < length; i++) {
if (handlers[i] === listener ||
(handlers[i].listener && handlers[i].listener === listener) ||
(handlers[i]._origin && handlers[i]._origin === listener)) {
position = i;
break;
}
}
if (position < 0) {
return this;
}
if(this.wildcard) {
leaf._listeners.splice(position, 1)
}
else {
this._events[type].splice(position, 1);
}
if (handlers.length === 0) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
else if (handlers === listener ||
(handlers.listener && handlers.listener === listener) ||
(handlers._origin && handlers._origin === listener)) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
return this;
};
EventEmitter.prototype.offAny = function(fn) {
var i = 0, l = 0, fns;
if (fn && this._all && this._all.length > 0) {
fns = this._all;
for(i = 0, l = fns.length; i < l; i++) {
if(fn === fns[i]) {
fns.splice(i, 1);
return this;
}
}
} else {
this._all = [];
}
return this;
};
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
!this._events || init.call(this);
return this;
}
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
leaf._listeners = null;
}
}
else {
if (!this._events[type]) return this;
this._events[type] = null;
}
return this;
};
EventEmitter.prototype.listeners = function(type) {
if(this.wildcard) {
var handlers = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
return handlers;
}
this._events || init.call(this);
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
EventEmitter.prototype.listenersAny = function() {
if(this._all) {
return this._all;
}
else {
return [];
}
};
// if (typeof define === 'function' && define.amd) {
// define('EventEmitter2', [], function() {
// return EventEmitter;
// });
// } else {
exports.EventEmitter2 = EventEmitter;
// }
}(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window);
/*!
* Øyvind Sean Kinsey and others require the following notice to accompany easyXDM:
*
* http://easyxdm.net/
* Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) {
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */
var global = this;
var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded
var emptyFn = Function.prototype;
var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4)
var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression
var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global)
var easyXDM = {};
var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite
var IFRAME_PREFIX = "easyXDM_";
var HAS_NAME_PROPERTY_BUG;
var useHash = false; // whether to use the hash over the query
var flashVersion; // will be set if using flash
var HAS_FLASH_THROTTLED_BUG;
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
// end
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
function isArray(o){
return Object.prototype.toString.call(o) === '[object Array]';
}
// end
function hasFlash(){
try {
var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1);
HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0;
activeX = null;
return true;
}
catch (notSupportedException) {
return false;
}
}
/*
* Cross Browser implementation for adding and removing event listeners.
*/
var on, un;
if (isHostMethod(window, "addEventListener")) {
on = function(target, type, listener){
target.addEventListener(type, listener, false);
};
un = function(target, type, listener){
target.removeEventListener(type, listener, false);
};
}
else if (isHostMethod(window, "attachEvent")) {
on = function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
un = function(object, sEvent, fpNotify){
object.detachEvent("on" + sEvent, fpNotify);
};
}
else {
throw new Error("Browser not supported");
}
/*
* Cross Browser implementation of DOMContentLoaded.
*/
var domIsReady = false, domReadyQueue = [], readyState;
if ("readyState" in document) {
// If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and
// 'interactive' (HTML5 specs, recent WebKit builds) states.
// https://bugs.webkit.org/show_bug.cgi?id=45119
readyState = document.readyState;
domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive"));
}
else {
// If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately
// when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not.
// We only need a body to add elements to, so the existence of document.body is enough for us.
domIsReady = !!document.body;
}
function dom_onReady(){
if (domIsReady) {
return;
}
domIsReady = true;
for (var i = 0; i < domReadyQueue.length; i++) {
domReadyQueue[i]();
}
domReadyQueue.length = 0;
}
if (!domIsReady) {
if (isHostMethod(window, "addEventListener")) {
on(document, "DOMContentLoaded", dom_onReady);
}
else {
on(document, "readystatechange", function(){
if (document.readyState == "complete") {
dom_onReady();
}
});
if (document.documentElement.doScroll && window === top) {
var doScrollCheck = function(){
if (domIsReady) {
return;
}
// http://javascript.nwbox.com/IEContentLoaded/
try {
document.documentElement.doScroll("left");
}
catch (e) {
setTimeout(doScrollCheck, 1);
return;
}
dom_onReady();
};
doScrollCheck();
}
}
// A fallback to window.onload, that will always work
on(window, "load", dom_onReady);
}
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {Object} scope An optional scope for the function to be called with.
*/
function whenReady(fn, scope){
if (domIsReady) {
fn.call(scope);
return;
}
domReadyQueue.push(function(){
fn.call(scope);
});
}
/**
* Returns an instance of easyXDM from the parent window with
* respect to the namespace.
*
* @return An instance of easyXDM (in the parent window)
*/
function getParentObject(){
var obj = parent;
if (namespace !== "") {
for (var i = 0, ii = namespace.split("."); i < ii.length; i++) {
obj = obj[ii[i]];
}
}
return obj.easyXDM;
}
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
function noConflict(ns){
window.easyXDM = _easyXDM;
namespace = ns;
if (namespace) {
IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_";
}
return easyXDM;
}
/*
* Methods for working with URLs
*/
/**
* Get the domain name from a url.
* @param {String} url The url to extract the domain from.
* @return The domain part of the url.
* @type {String}
*/
function getDomainName(url){
return url.match(reURI)[3];
}
/**
* Get the port for a given URL, or "" if none
* @param {String} url The url to extract the port from.
* @return The port part of the url.
* @type {String}
*/
function getPort(url){
return url.match(reURI)[4] || "";
}
/**
* Returns a string containing the schema, domain and if present the port
* @param {String} url The url to extract the location from
* @return {String} The location part of the url
*/
function getLocation(url){
var m = url.toLowerCase().match(reURI);
var proto = m[2], domain = m[3], port = m[4] || "";
if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) {
port = "";
}
return proto + "//" + domain + port;
}
/**
* Resolves a relative url into an absolute one.
* @param {String} url The path to resolve.
* @return {String} The resolved url.
*/
function resolveUrl(url){
// replace all // except the one in proto with /
url = url.replace(reDoubleSlash, "$1/");
// If the url is a valid url we do nothing
if (!url.match(/^(http||https):\/\//)) {
// If this is a relative path
var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
if (path.substring(path.length - 1) !== "/") {
path = path.substring(0, path.lastIndexOf("/") + 1);
}
url = location.protocol + "//" + location.host + path + url;
}
// reduce all 'xyz/../' to just ''
while (reParent.test(url)) {
url = url.replace(reParent, "");
}
return url;
}
/**
* Appends the parameters to the given url.<br/>
* The base url can contain existing query parameters.
* @param {String} url The base url.
* @param {Object} parameters The parameters to add.
* @return {String} A new valid url with the parameters appended.
*/
function appendQueryParameters(url, parameters){
var hash = "", indexOf = url.indexOf("#");
if (indexOf !== -1) {
hash = url.substring(indexOf);
url = url.substring(0, indexOf);
}
var q = [];
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
q.push(key + "=" + encodeURIComponent(parameters[key]));
}
}
return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash;
}
// build the query object either from location.query, if it contains the xdm_e argument, or from location.hash
var query = (function(input){
input = input.substring(1).split("&");
var data = {}, pair, i = input.length;
while (i--) {
pair = input[i].split("=");
data[pair[0]] = decodeURIComponent(pair[1]);
}
return data;
}(/xdm_e=/.test(location.search) ? location.search : location.hash));
/*
* Helper methods
*/
/**
* Helper for checking if a variable/property is undefined
* @param {Object} v The variable to test
* @return {Boolean} True if the passed variable is undefined
*/
function undef(v){
return typeof v === "undefined";
}
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
var getJSON = function(){
var cached = {};
var obj = {
a: [1, 2, 3]
}, json = "{\"a\":[1,2,3]}";
if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) {
// this is a working JSON instance
return JSON;
}
if (Object.toJSON) {
if (Object.toJSON(obj).replace((/\s/g), "") === json) {
// this is a working stringify method
cached.stringify = Object.toJSON;
}
}
if (typeof String.prototype.evalJSON === "function") {
obj = json.evalJSON();
if (obj.a && obj.a.length === 3 && obj.a[2] === 3) {
// this is a working parse method
cached.parse = function(str){
return str.evalJSON();
};
}
}
if (cached.stringify && cached.parse) {
// Only memoize the result if we have valid instance
getJSON = function(){
return cached;
};
return cached;
}
return null;
};
/**
* Applies properties from the source object to the target object.<br/>
* @param {Object} target The target of the properties.
* @param {Object} source The source of the properties.
* @param {Boolean} noOverwrite Set to True to only set non-existing properties.
*/
function apply(destination, source, noOverwrite){
var member;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (prop in destination) {
member = source[prop];
if (typeof member === "object") {
apply(destination[prop], member, noOverwrite);
}
else if (!noOverwrite) {
destination[prop] = source[prop];
}
}
else {
destination[prop] = source[prop];
}
}
}
return destination;
}
// This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName].
function testForNamePropertyBug(){
var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input"));
input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues
HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name];
document.body.removeChild(form);
}
/**
* Creates a frame and appends it to the DOM.
* @param config {object} This object can have the following properties
* <ul>
* <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li>
* <li> {object} attr The attributes that should be set on the frame.</li>
* <li> {DOMElement} container Its parent element (Optional).</li>
* <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li>
* </ul>
* @return The frames DOMElement
* @type DOMElement
*/
function createFrame(config){
if (undef(HAS_NAME_PROPERTY_BUG)) {
testForNamePropertyBug();
}
var frame;
// This is to work around the problems in IE6/7 with setting the name property.
// Internally this is set as 'submitName' instead when using 'iframe.name = ...'
// This is not required by easyXDM itself, but is to facilitate other use cases
if (HAS_NAME_PROPERTY_BUG) {
frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>");
}
else {
frame = document.createElement("IFRAME");
frame.name = config.props.name;
}
frame.id = frame.name = config.props.name;
delete config.props.name;
if (config.onLoad) {
on(frame, "load", config.onLoad);
}
if (typeof config.container == "string") {
config.container = document.getElementById(config.container);
}
if (!config.container) {
// This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers.
apply(frame.style, {
position: "absolute",
top: "-2000px"
});
config.container = document.body;
}
// HACK for some reason, IE needs the source set
// after the frame has been appended into the DOM
// so remove the src, and set it afterwards
var src = config.props.src;
delete config.props.src;
// transfer properties to the frame
apply(frame, config.props);
frame.border = frame.frameBorder = 0;
frame.allowTransparency = true;
config.container.appendChild(frame);
// HACK see above
frame.src = src;
config.props.src = src;
return frame;
}
/**
* Check whether a domain is allowed using an Access Control List.
* The ACL can contain * and ? as wildcards, or can be regular expressions.
* If regular expressions they need to begin with ^ and end with $.
* @param {Array/String} acl The list of allowed domains
* @param {String} domain The domain to test.
* @return {Boolean} True if the domain is allowed, false if not.
*/
function checkAcl(acl, domain){
// normalize into an array
if (typeof acl == "string") {
acl = [acl];
}
var re, i = acl.length;
while (i--) {
re = acl[i];
re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$"));
if (re.test(domain)) {
return true;
}
}
return false;
}
/*
* Functions related to stacks
*/
/**
* Prepares an array of stack-elements suitable for the current configuration
* @param {Object} config The Transports configuration. See easyXDM.Socket for more.
* @return {Array} An array of stack-elements with the TransportElement at index 0.
*/
function prepareTransportStack(config){
var protocol = config.protocol, stackEls;
config.isHost = config.isHost || undef(query.xdm_p);
useHash = config.hash || false;
if (!config.props) {
config.props = {};
}
if (!config.isHost) {
config.channel = query.xdm_c;
config.secret = query.xdm_s;
config.remote = query.xdm_e;
protocol = query.xdm_p;
if (config.acl && !checkAcl(config.acl, config.remote)) {
throw new Error("Access denied for " + config.remote);
}
}
else {
config.remote = resolveUrl(config.remote);
config.channel = config.channel || "default" + channelId++;
config.secret = Math.random().toString(16).substring(2);
if (undef(protocol)) {
if (getLocation(location.href) == getLocation(config.remote)) {
/*
* Both documents has the same origin, lets use direct access.
*/
protocol = "4";
}
else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) {
/*
* This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+
*/
protocol = "1";
}
else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) {
/*
* The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS
*/
protocol = "6";
}
else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) {
/*
* This is supported in Gecko (Firefox 1+)
*/
protocol = "5";
}
else if (config.remoteHelper) {
/*
* This is supported in all browsers that retains the value of window.name when
* navigating from one domain to another, and where parent.frames[foo] can be used
* to get access to a frame from the same domain
*/
config.remoteHelper = resolveUrl(config.remoteHelper);
protocol = "2";
}
else {
/*
* This is supported in all browsers where [window].location is writable for all
* The resize event will be used if resize is supported and the iframe is not put
* into a container, else polling will be used.
*/
protocol = "0";
}
}
}
config.protocol = protocol; // for conditional branching
switch (protocol) {
case "0":// 0 = HashTransport
apply(config, {
interval: 100,
delay: 2000,
useResize: true,
useParent: false,
usePolling: false
}, true);
if (config.isHost) {
if (!config.local) {
// If no local is set then we need to find an image hosted on the current domain
var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image;
var i = images.length;
while (i--) {
image = images[i];
if (image.src.substring(0, domain.length) === domain) {
config.local = image.src;
break;
}
}
if (!config.local) {
// If no local was set, and we are unable to find a suitable file, then we resort to using the current window
config.local = window;
}
}
var parameters = {
xdm_c: config.channel,
xdm_p: 0
};
if (config.local === window) {
// We are using the current window to listen to
config.usePolling = true;
config.useParent = true;
config.local = location.protocol + "//" + location.host + location.pathname + location.search;
parameters.xdm_e = config.local;
parameters.xdm_pa = 1; // use parent
}
else {
parameters.xdm_e = resolveUrl(config.local);
}
if (config.container) {
config.useResize = false;
parameters.xdm_po = 1; // use polling
}
config.remote = appendQueryParameters(config.remote, parameters);
}
else {
apply(config, {
channel: query.xdm_c,
remote: query.xdm_e,
useParent: !undef(query.xdm_pa),
usePolling: !undef(query.xdm_po),
useResize: config.useParent ? false : config.useResize
});
}
stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({
encode: true,
maxLength: 4000 - config.remote.length
}), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "1":
stackEls = [new easyXDM.stack.PostMessageTransport(config)];
break;
case "2":
stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "3":
stackEls = [new easyXDM.stack.NixTransport(config)];
break;
case "4":
stackEls = [new easyXDM.stack.SameOriginTransport(config)];
break;
case "5":
stackEls = [new easyXDM.stack.FrameElementTransport(config)];
break;
case "6":
if (!flashVersion) {
hasFlash();
}
stackEls = [new easyXDM.stack.FlashTransport(config)];
break;
}
// this behavior is responsible for buffering outgoing messages, and for performing lazy initialization
stackEls.push(new easyXDM.stack.QueueBehavior({
lazy: config.lazy,
remove: true
}));
return stackEls;
}
/**
* Chains all the separate stack elements into a single usable stack.<br/>
* If an element is missing a necessary method then it will have a pass-through method applied.
* @param {Array} stackElements An array of stack elements to be linked.
* @return {easyXDM.stack.StackElement} The last element in the chain.
*/
function chainStack(stackElements){
var stackEl, defaults = {
incoming: function(message, origin){
this.up.incoming(message, origin);
},
outgoing: function(message, recipient){
this.down.outgoing(message, recipient);
},
callback: function(success){
this.up.callback(success);
},
init: function(){
this.down.init();
},
destroy: function(){
this.down.destroy();
}
};
for (var i = 0, len = stackElements.length; i < len; i++) {
stackEl = stackElements[i];
apply(stackEl, defaults, true);
if (i !== 0) {
stackEl.down = stackElements[i - 1];
}
if (i !== len - 1) {
stackEl.up = stackElements[i + 1];
}
}
return stackEl;
}
/**
* This will remove a stackelement from its stack while leaving the stack functional.
* @param {Object} element The elment to remove from the stack.
*/
function removeFromStack(element){
element.up.down = element.down;
element.down.up = element.up;
element.up = element.down = null;
}
/*
* Export the main object and any other methods applicable
*/
/**
* @class easyXDM
* A javascript library providing cross-browser, cross-domain messaging/RPC.
* @version 2.4.15.118
* @singleton
*/
apply(easyXDM, {
/**
* The version of the library
* @type {string}
*/
version: "2.4.15.118",
/**
* This is a map containing all the query parameters passed to the document.
* All the values has been decoded using decodeURIComponent.
* @type {object}
*/
query: query,
/**
* @private
*/
stack: {},
/**
* Applies properties from the source object to the target object.<br/>
* @param {object} target The target of the properties.
* @param {object} source The source of the properties.
* @param {boolean} noOverwrite Set to True to only set non-existing properties.
*/
apply: apply,
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
getJSONObject: getJSON,
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {object} scope An optional scope for the function to be called with.
*/
whenReady: whenReady,
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
noConflict: noConflict
});
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.DomHelper
* Contains methods for dealing with the DOM
* @singleton
*/
easyXDM.DomHelper = {
/**
* Provides a consistent interface for adding eventhandlers
* @param {Object} target The target to add the event to
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
on: on,
/**
* Provides a consistent interface for removing eventhandlers
* @param {Object} target The target to remove the event from
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
un: un,
/**
* Checks for the presence of the JSON object.
* If it is not present it will use the supplied path to load the JSON2 library.
* This should be called in the documents head right after the easyXDM script tag.
* http://json.org/json2.js
* @param {String} path A valid path to json2.js
*/
requiresJSON: function(path){
if (!isHostObject(window, "JSON")) {
// we need to encode the < in order to avoid an illegal token error
// when the script is inlined in a document.
document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>');
}
}
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
(function(){
// The map containing the stored functions
var _map = {};
/**
* @class easyXDM.Fn
* This contains methods related to function handling, such as storing callbacks.
* @singleton
* @namespace easyXDM
*/
easyXDM.Fn = {
/**
* Stores a function using the given name for reference
* @param {String} name The name that the function should be referred by
* @param {Function} fn The function to store
* @namespace easyXDM.fn
*/
set: function(name, fn){
_map[name] = fn;
},
/**
* Retrieves the function referred to by the given name
* @param {String} name The name of the function to retrieve
* @param {Boolean} del If the function should be deleted after retrieval
* @return {Function} The stored function
* @namespace easyXDM.fn
*/
get: function(name, del){
var fn = _map[name];
if (del) {
delete _map[name];
}
return fn;
}
};
}());
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.Socket
* This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/>
* The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/>
* Internally different stacks will be used depending on the browsers features and the available parameters.
* <h2>How to set up</h2>
* Setting up the provider:
* <pre><code>
* var socket = new easyXDM.Socket({
* local: "name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* Setting up the consumer:
* <pre><code>
* var socket = new easyXDM.Socket({
* remote: "http://remotedomain/page.html",
* remoteHelper: "http://remotedomain/name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property
* and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports.
* @namespace easyXDM
* @constructor
* @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window.
* @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed.
* @cfg {String} remote (Consumer only) The url to the providers document.
* @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000.
* @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300.
* @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional.
* @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional.
* @cfg {Function} onReady A method that should be called when the transport is ready. Optional.
* @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional.
* @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/>
* This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $.
* If none of the patterns match an Error will be thrown.
* @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>.
* Properties such as 'name' and 'src' will be overrided. Optional.
*/
easyXDM.Socket = function(config){
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([{
incoming: function(message, origin){
config.onMessage(message, origin);
},
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}])), recipient = getLocation(config.remote);
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
/**
* Posts a message to the remote end of the channel
* @param {String} message The message to send
*/
this.postMessage = function(message){
stack.outgoing(message, recipient);
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.Rpc
* Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation
* of methods to be called from the remote end.<br/>
* The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/>
* This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods.
* <h2>How to set up</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* // this configuration is equal to that used by the Socket.
* remote: "http://remotedomain/...",
* onReady: function(){
* // you need to wait for the onReady callback before using the proxy
* rpc.foo(...
* }
* },{
* local: {..},
* remote: {..}
* });
* </code></pre>
*
* <h2>Exposing functions (procedures)</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {
* nameOfMethod: {
* method: function(arg1, arg2, success, error){
* ...
* }
* },
* // with shorthand notation
* nameOfAnotherMethod: function(arg1, arg2, success, error){
* }
* },
* remote: {...}
* });
* </code></pre>
* The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/>
* To send a successfull result back you can use
* <pre><code>
* return foo;
* </pre></code>
* or
* <pre><code>
* success(foo);
* </pre></code>
* To return an error you can use
* <pre><code>
* throw new Error("foo error");
* </code></pre>
* or
* <pre><code>
* error("foo error");
* </code></pre>
*
* <h2>Defining remotely exposed methods (procedures/notifications)</h2>
* The definition of the remote end is quite similar:
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {
* nameOfMethod: {}
* }
* });
* </code></pre>
* To call a remote method use
* <pre><code>
* rpc.nameOfMethod("arg1", "arg2", function(value) {
* alert("success: " + value);
* }, function(message) {
* alert("error: " + message + );
* });
* </code></pre>
* Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/>
* When called with no callback a JSON-RPC 2.0 notification will be executed.
* Be aware that you will not be notified of any errors with this method.
* <br/>
* <h2>Specifying a custom serializer</h2>
* If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library
* then you can specify a custom serializer using <code>serializer: foo</code>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {...},
* serializer : {
* parse: function(string){ ... },
* stringify: function(object) {...}
* }
* });
* </code></pre>
* If <code>serializer</code> is set then the class will not attempt to use the native implementation.
* @namespace easyXDM
* @constructor
* @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters.
* @param {Object} jsonRpcConfig The description of the interface to implement.
*/
easyXDM.Rpc = function(config, jsonRpcConfig){
// expand shorthand notation
if (jsonRpcConfig.local) {
for (var method in jsonRpcConfig.local) {
if (jsonRpcConfig.local.hasOwnProperty(method)) {
var member = jsonRpcConfig.local[method];
if (typeof member === "function") {
jsonRpcConfig.local[method] = {
method: member
};
}
}
}
}
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), {
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}]));
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.SameOriginTransport
* SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/>
* This can be useful for testing and for when the main application supports both internal and external sources.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.SameOriginTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send(message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: location.protocol + "//" + location.host + location.pathname,
xdm_c: config.channel,
xdm_p: 4 // 4 = SameOriginTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
easyXDM.Fn.set(config.channel, function(sendFn){
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
});
}
else {
send = getParentObject().Fn.get(config.channel, true)(function(msg){
pub.up.incoming(msg, targetOrigin);
});
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.FlashTransport
* FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
* @cfg {String} secret the pre-shared secret used to secure the communication.
* @cfg {String} swf The path to the swf file
* @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden.
* @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed
*/
easyXDM.stack.FlashTransport = function(config){
var pub, // the public interface
frame, send, targetOrigin, swf, swfContainer;
function onMessage(message, origin){
setTimeout(function(){
pub.up.incoming(message, targetOrigin);
}, 0);
}
/**
* This method adds the SWF to the DOM and prepares the initialization of the channel
*/
function addSwf(domain){
// the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.
var url = config.swf + "?host=" + config.isHost;
var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
// prepare the init function that will fire once the swf is ready
easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){
easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;
var queue = easyXDM.stack.FlashTransport[domain].queue;
for (var i = 0; i < queue.length; i++) {
queue[i]();
}
queue.length = 0;
});
if (config.swfContainer) {
swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer;
}
else {
// create the container that will hold the swf
swfContainer = document.createElement('div');
// http://bugs.adobe.com/jira/browse/FP-4796
// http://tech.groups.yahoo.com/group/flexcoders/message/162365
// https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc
apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {
height: "20px",
width: "20px",
position: "fixed",
right: 0,
top: 0
} : {
height: "1px",
width: "1px",
position: "absolute",
overflow: "hidden",
right: 0,
top: 0
});
document.body.appendChild(swfContainer);
}
// create the object/embed
var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace;
swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" +
"<param name='allowScriptAccess' value='always'></param>" +
"<param name='wmode' value='transparent'>" +
"<param name='movie' value='" +
url +
"'></param>" +
"<param name='flashvars' value='" +
flashVars +
"'></param>" +
"<embed type='application/x-shockwave-flash' FlashVars='" +
flashVars +
"' allowScriptAccess='always' wmode='transparent' src='" +
url +
"' height='1' width='1'></embed>" +
"</object>";
}
return (pub = {
outgoing: function(message, domain, fn){
swf.postMessage(config.channel, message.toString());
if (fn) {
fn();
}
},
destroy: function(){
try {
swf.destroyChannel(config.channel);
}
catch (e) {
}
swf = null;
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = config.remote;
// Prepare the code that will be run after the swf has been intialized
easyXDM.Fn.set("flash_" + config.channel + "_init", function(){
setTimeout(function(){
pub.up.callback(true);
});
});
// set up the omMessage handler
easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths
var swfdomain = getDomainName(config.swf);
var fn = function(){
// set init to true in case the fn was called was invoked from a separate instance
easyXDM.stack.FlashTransport[swfdomain].init = true;
swf = easyXDM.stack.FlashTransport[swfdomain].swf;
// create the channel
swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost);
if (config.isHost) {
// if Flash is going to be throttled and we want to avoid this
if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) {
apply(config.props, {
position: "fixed",
right: 0,
top: 0,
height: "20px",
width: "20px"
});
}
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 6, // 6 = FlashTransport
xdm_s: config.secret
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
};
if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) {
// if the swf is in place and we are the consumer
fn();
}
else {
// if the swf does not yet exist
if (!easyXDM.stack.FlashTransport[swfdomain]) {
// add the queue to hold the init fn's
easyXDM.stack.FlashTransport[swfdomain] = {
queue: [fn]
};
addSwf(swfdomain);
}
else {
easyXDM.stack.FlashTransport[swfdomain].queue.push(fn);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.PostMessageTransport
* PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/>
* <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
*/
easyXDM.stack.PostMessageTransport = function(config){
var pub, // the public interface
frame, // the remote frame, if any
callerWindow, // the window that we will call with
targetOrigin; // the domain to communicate with
/**
* Resolves the origin from the event object
* @private
* @param {Object} event The messageevent
* @return {String} The scheme, host and port of the origin
*/
function _getOrigin(event){
if (event.origin) {
// This is the HTML5 property
return getLocation(event.origin);
}
if (event.uri) {
// From earlier implementations
return getLocation(event.uri);
}
if (event.domain) {
// This is the last option and will fail if the
// origin is not using the same schema as we are
return location.protocol + "//" + event.domain;
}
throw "Unable to retrieve the origin of the event";
}
/**
* This is the main implementation for the onMessage event.<br/>
* It checks the validity of the origin and passes the message on if appropriate.
* @private
* @param {Object} event The messageevent
*/
function _window_onMessage(event){
var origin = _getOrigin(event);
if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") {
pub.up.incoming(event.data.substring(config.channel.length + 1), origin);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin);
if (fn) {
fn();
}
},
destroy: function(){
un(window, "message", _window_onMessage);
if (frame) {
callerWindow = null;
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// add the event handler for listening
var waitForReady = function(event){
if (event.data == config.channel + "-ready") {
// replace the eventlistener
callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document;
un(window, "message", waitForReady);
on(window, "message", _window_onMessage);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
};
on(window, "message", waitForReady);
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 1 // 1 = PostMessage
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
else {
// add the event handler for listening
on(window, "message", _window_onMessage);
callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document;
callerWindow.postMessage(config.channel + "-ready", targetOrigin);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.FrameElementTransport
* FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/>
* Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.FrameElementTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send.call(this, message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 5 // 5 = FrameElementTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
frame.fn = function(sendFn){
delete frame.fn;
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
// remove the function so that it cannot be used to overwrite the send function later on
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
};
}
else {
// This is to mitigate origin-spoofing
if (document.referrer && getLocation(document.referrer) != query.xdm_e) {
window.top.location = query.xdm_e;
}
send = window.frameElement.fn(function(msg){
pub.up.incoming(msg, targetOrigin);
});
pub.up.callback(true);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.NameTransport
* NameTransport uses the window.name property to relay data.
* The <code>local</code> parameter needs to be set on both the consumer and provider,<br/>
* and the <code>remoteHelper</code> parameter needs to be set on the consumer.
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host.
* @namespace easyXDM.stack
*/
easyXDM.stack.NameTransport = function(config){
var pub; // the public interface
var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl;
function _sendMessage(message){
var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel;
callerWindow.contentWindow.sendMessage(message, url);
}
function _onReady(){
if (isHost) {
if (++readyCount === 2 || !isHost) {
pub.up.callback(true);
}
}
else {
_sendMessage("ready");
pub.up.callback(true);
}
}
function _onMessage(message){
pub.up.incoming(message, remoteOrigin);
}
function _onLoad(){
if (callback) {
setTimeout(function(){
callback(true);
}, 0);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callback = fn;
_sendMessage(message);
},
destroy: function(){
callerWindow.parentNode.removeChild(callerWindow);
callerWindow = null;
if (isHost) {
remoteWindow.parentNode.removeChild(remoteWindow);
remoteWindow = null;
}
},
onDOMReady: function(){
isHost = config.isHost;
readyCount = 0;
remoteOrigin = getLocation(config.remote);
config.local = resolveUrl(config.local);
if (isHost) {
// Register the callback
easyXDM.Fn.set(config.channel, function(message){
if (isHost && message === "ready") {
// Replace the handler
easyXDM.Fn.set(config.channel, _onMessage);
_onReady();
}
});
// Set up the frame that points to the remote instance
remoteUrl = appendQueryParameters(config.remote, {
xdm_e: config.local,
xdm_c: config.channel,
xdm_p: 2
});
apply(config.props, {
src: remoteUrl + '#' + config.channel,
name: IFRAME_PREFIX + config.channel + "_provider"
});
remoteWindow = createFrame(config);
}
else {
config.remoteHelper = config.remote;
easyXDM.Fn.set(config.channel, _onMessage);
}
// Set up the iframe that will be used for the transport
callerWindow = createFrame({
props: {
src: config.local + "#_4" + config.channel
},
onLoad: function onLoad(){
// Remove the handler
var w = callerWindow || this;
un(w, "load", onLoad);
easyXDM.Fn.set(config.channel + "_load", _onLoad);
(function test(){
if (typeof w.contentWindow.sendMessage == "function") {
_onReady();
}
else {
setTimeout(test, 50);
}
}());
}
});
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.HashTransport
* HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
* @cfg {Number} interval The interval used when polling for messages.
*/
easyXDM.stack.HashTransport = function(config){
var pub;
var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
var useParent, _remoteOrigin;
function _sendMessage(message){
if (!_callerWindow) {
return;
}
var url = config.remote + "#" + (_msgNr++) + "_" + message;
((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url;
}
function _handleHash(hash){
_lastMsg = hash;
pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
}
/**
* Checks location.hash for a new message and relays this to the receiver.
* @private
*/
function _pollHash(){
if (!_listenerWindow) {
return;
}
var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#");
if (indexOf != -1) {
hash = href.substring(indexOf);
}
if (hash && hash != _lastMsg) {
_handleHash(hash);
}
}
function _attachListeners(){
_timer = setInterval(_pollHash, pollInterval);
}
return (pub = {
outgoing: function(message, domain){
_sendMessage(message);
},
destroy: function(){
window.clearInterval(_timer);
if (isHost || !useParent) {
_callerWindow.parentNode.removeChild(_callerWindow);
}
_callerWindow = null;
},
onDOMReady: function(){
isHost = config.isHost;
pollInterval = config.interval;
_lastMsg = "#" + config.channel;
_msgNr = 0;
useParent = config.useParent;
_remoteOrigin = getLocation(config.remote);
if (isHost) {
config.props = {
src: config.remote,
name: IFRAME_PREFIX + config.channel + "_provider"
};
if (useParent) {
config.onLoad = function(){
_listenerWindow = window;
_attachListeners();
pub.up.callback(true);
};
}
else {
var tries = 0, max = config.delay / 50;
(function getRef(){
if (++tries > max) {
throw new Error("Unable to reference listenerwindow");
}
try {
_listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"];
}
catch (ex) {
}
if (_listenerWindow) {
_attachListeners();
pub.up.callback(true);
}
else {
setTimeout(getRef, 50);
}
}());
}
_callerWindow = createFrame(config);
}
else {
_listenerWindow = window;
_attachListeners();
if (useParent) {
_callerWindow = parent;
pub.up.callback(true);
}
else {
apply(config, {
props: {
src: config.remote + "#" + config.channel + new Date(),
name: IFRAME_PREFIX + config.channel + "_consumer"
},
onLoad: function(){
pub.up.callback(true);
}
});
_callerWindow = createFrame(config);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.ReliableBehavior
* This is a behavior that tries to make the underlying transport reliable by using acknowledgements.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
*/
easyXDM.stack.ReliableBehavior = function(config){
var pub, // the public interface
callback; // the callback to execute when we have a confirmed success/failure
var idOut = 0, idIn = 0, currentMessage = "";
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(",");
message = message.substring(indexOf + 1);
if (ack[0] == idOut) {
currentMessage = "";
if (callback) {
callback(true);
}
}
if (message.length > 0) {
pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin);
if (idIn != ack[1]) {
idIn = ack[1];
pub.up.incoming(message, origin);
}
}
},
outgoing: function(message, origin, fn){
currentMessage = message;
callback = fn;
pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.QueueBehavior
* This is a behavior that enables queueing of messages. <br/>
* It will buffer incoming messages and dispach these as fast as the underlying transport allows.
* This will also fragment/defragment messages so that the outgoing message is never bigger than the
* set length.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration. Optional.
* @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation.
*/
easyXDM.stack.QueueBehavior = function(config){
var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false;
function dispatch(){
if (config.remove && queue.length === 0) {
removeFromStack(pub);
return;
}
if (waiting || queue.length === 0 || destroying) {
return;
}
waiting = true;
var message = queue.shift();
pub.down.outgoing(message.data, message.origin, function(success){
waiting = false;
if (message.callback) {
setTimeout(function(){
message.callback(success);
}, 0);
}
dispatch();
});
}
return (pub = {
init: function(){
if (undef(config)) {
config = {};
}
if (config.maxLength) {
maxLength = config.maxLength;
doFragment = true;
}
if (config.lazy) {
lazy = true;
}
else {
pub.down.init();
}
},
callback: function(success){
waiting = false;
var up = pub.up; // in case dispatch calls removeFromStack
dispatch();
up.callback(success);
},
incoming: function(message, origin){
if (doFragment) {
var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10);
incoming += message.substring(indexOf + 1);
if (seq === 0) {
if (config.encode) {
incoming = decodeURIComponent(incoming);
}
pub.up.incoming(incoming, origin);
incoming = "";
}
}
else {
pub.up.incoming(message, origin);
}
},
outgoing: function(message, origin, fn){
if (config.encode) {
message = encodeURIComponent(message);
}
var fragments = [], fragment;
if (doFragment) {
// fragment into chunks
while (message.length !== 0) {
fragment = message.substring(0, maxLength);
message = message.substring(fragment.length);
fragments.push(fragment);
}
// enqueue the chunks
while ((fragment = fragments.shift())) {
queue.push({
data: fragments.length + "_" + fragment,
origin: origin,
callback: fragments.length === 0 ? fn : null
});
}
}
else {
queue.push({
data: message,
origin: origin,
callback: fn
});
}
if (lazy) {
pub.down.init();
}
else {
dispatch();
}
},
destroy: function(){
destroying = true;
pub.down.destroy();
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.VerifyBehavior
* This behavior will verify that communication with the remote end is possible, and will also sign all outgoing,
* and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
* @cfg {Boolean} initiate If the verification should be initiated from this end.
*/
easyXDM.stack.VerifyBehavior = function(config){
var pub, mySecret, theirSecret, verified = false;
function startVerification(){
mySecret = Math.random().toString(16).substring(2);
pub.down.outgoing(mySecret);
}
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_");
if (indexOf === -1) {
if (message === mySecret) {
pub.up.callback(true);
}
else if (!theirSecret) {
theirSecret = message;
if (!config.initiate) {
startVerification();
}
pub.down.outgoing(message);
}
}
else {
if (message.substring(0, indexOf) === theirSecret) {
pub.up.incoming(message.substring(indexOf + 1), origin);
}
}
},
outgoing: function(message, origin, fn){
pub.down.outgoing(mySecret + "_" + message, origin, fn);
},
callback: function(success){
if (config.initiate) {
startVerification();
}
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, [email protected].
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/**
* @class easyXDM.stack.RpcBehavior
* This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/>
* Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything.
* @namespace easyXDM.stack
* @constructor
* @param {Object} proxy The object to apply the methods to.
* @param {Object} config The definition of the local and remote interface to implement.
* @cfg {Object} local The local interface to expose.
* @cfg {Object} remote The remote methods to expose through the proxy.
* @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON.
*/
easyXDM.stack.RpcBehavior = function(proxy, config){
var pub, serializer = config.serializer || getJSON();
var _callbackCounter = 0, _callbacks = {};
/**
* Serializes and sends the message
* @private
* @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added.
*/
function _send(data){
data.jsonrpc = "2.0";
pub.down.outgoing(serializer.stringify(data));
}
/**
* Creates a method that implements the given definition
* @private
* @param {Object} The method configuration
* @param {String} method The name of the method
* @return {Function} A stub capable of proxying the requested method call
*/
function _createMethod(definition, method){
var slice = Array.prototype.slice;
return function(){
var l = arguments.length, callback, message = {
method: method
};
if (l > 0 && typeof arguments[l - 1] === "function") {
//with callback, procedure
if (l > 1 && typeof arguments[l - 2] === "function") {
// two callbacks, success and error
callback = {
success: arguments[l - 2],
error: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 2);
}
else {
// single callback, success
callback = {
success: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 1);
}
_callbacks["" + (++_callbackCounter)] = callback;
message.id = _callbackCounter;
}
else {
// no callbacks, a notification
message.params = slice.call(arguments, 0);
}
if (definition.namedParams && message.params.length === 1) {
message.params = message.params[0];
}
// Send the method request
_send(message);
};
}
/**
* Executes the exposed method
* @private
* @param {String} method The name of the method
* @param {Number} id The callback id to use
* @param {Function} method The exposed implementation
* @param {Array} params The parameters supplied by the remote end
*/
function _executeMethod(method, id, fn, params){
if (!fn) {
if (id) {
_send({
id: id,
error: {
code: -32601,
message: "Procedure not found."
}
});
}
return;
}
var success, error;
if (id) {
success = function(result){
success = emptyFn;
_send({
id: id,
result: result
});
};
error = function(message, data){
error = emptyFn;
var msg = {
id: id,
error: {
code: -32099,
message: message
}
};
if (data) {
msg.error.data = data;
}
_send(msg);
};
}
else {
success = error = emptyFn;
}
// Call local method
if (!isArray(params)) {
params = [params];
}
try {
var result = fn.method.apply(fn.scope, params.concat([success, error]));
if (!undef(result)) {
success(result);
}
}
catch (ex1) {
error(ex1.message);
}
}
return (pub = {
incoming: function(message, origin){
var data = serializer.parse(message);
if (data.method) {
// A method call from the remote end
if (config.handle) {
config.handle(data, _send);
}
else {
_executeMethod(data.method, data.id, config.local[data.method], data.params);
}
}
else {
// A method response from the other end
var callback = _callbacks[data.id];
if (data.error) {
if (callback.error) {
callback.error(data.error);
}
}
else if (callback.success) {
callback.success(data.result);
}
delete _callbacks[data.id];
}
},
init: function(){
if (config.remote) {
// Implement the remote sides exposed methods
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method)) {
proxy[method] = _createMethod(config.remote[method], method);
}
}
}
pub.down.init();
},
destroy: function(){
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
delete proxy[method];
}
}
pub.down.destroy();
}
});
};
global.easyXDM = easyXDM;
})(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent);
/*!
* F2 v1.3.3 04-07-2014
* Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org
*
* "F2" is licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
* Please note that F2 ("Software") may contain third party material that Markit
* On Demand Inc. has a license to use and include within the Software (the
* "Third Party Material"). A list of the software comprising the Third Party Material
* and the terms and conditions under which such Third Party Material is distributed
* are reproduced in the ThirdPartyMaterial.md file available at:
*
* https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md
*
* The inclusion of the Third Party Material in the Software does not grant, provide
* nor result in you having acquiring any rights whatsoever, other than as stipulated
* in the terms and conditions related to the specific Third Party Material, if any.
*
*/
var F2;
/**
* Open F2
* @module f2
* @main f2
*/
F2 = (function() {
/**
* Abosolutizes a relative URL
* @method _absolutizeURI
* @private
* @param {e.g., location.href} base
* @param {URL to absolutize} href
* @returns {string} URL
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _absolutizeURI = function(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
href = _parseURI(href || '');
base = _parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
};
/**
* Parses URI
* @method _parseURI
* @private
* @param {The URL to parse} url
* @returns {Parsed URL} string
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _parseURI = function(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
};
return {
/**
* A function to pass into F2.stringify which will prevent circular
* reference errors when serializing objects
* @method appConfigReplacer
*/
appConfigReplacer: function(key, value) {
if (key == 'root' || key == 'ui' || key == 'height') {
return undefined;
} else {
return value;
}
},
/**
* The apps namespace is a place for app developers to put the javascript
* class that is used to initialize their app. The javascript classes should
* be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId.
* It is recommended that the code be placed in a closure to help keep the
* global namespace clean.
*
* If the class has an 'init' function, that function will be called
* automatically by F2.
* @property Apps
* @type object
* @example
* F2.Apps["com_example_helloworld"] = (function() {
* var App_Class = function(appConfig, appContent, root) {
* this._app = appConfig; // the F2.AppConfig object
* this._appContent = appContent // the F2.AppManifest.AppContent object
* this.$root = $(root); // the root DOM Element that contains this app
* }
*
* App_Class.prototype.init = function() {
* // perform init actions
* }
*
* return App_Class;
* })();
* @example
* F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) {
* return {
* init:function() {
* // perform init actions
* }
* };
* };
* @for F2
*/
Apps: {},
/**
* Creates a namespace on F2 and copies the contents of an object into
* that namespace optionally overwriting existing properties.
* @method extend
* @param {string} ns The namespace to create. Pass a falsy value to
* add properties to the F2 namespace directly.
* @param {object} obj The object to copy into the namespace.
* @param {bool} overwrite True if object properties should be overwritten
* @return {object} The created object
*/
extend: function (ns, obj, overwrite) {
var isFunc = typeof obj === 'function';
var parts = ns ? ns.split('.') : [];
var parent = this;
obj = obj || {};
// ignore leading global
if (parts[0] === 'F2') {
parts = parts.slice(1);
}
// create namespaces
for (var i = 0, len = parts.length; i < len; i++) {
if (!parent[parts[i]]) {
parent[parts[i]] = isFunc && i + 1 == len ? obj : {};
}
parent = parent[parts[i]];
}
// copy object into namespace
if (!isFunc) {
for (var prop in obj) {
if (typeof parent[prop] === 'undefined' || overwrite) {
parent[prop] = obj[prop];
}
}
}
return parent;
},
/**
* Generates a somewhat random id
* @method guid
* @return {string} A random id
* @for F2
*/
guid: function() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4());
},
/**
* Search for a value within an array.
* @method inArray
* @param {object} value The value to search for
* @param {Array} array The array to search
* @return {bool} True if the item is in the array
*/
inArray: function(value, array) {
return jQuery.inArray(value, array) > -1;
},
/**
* Tests a URL to see if it's on the same domain (local) or not
* @method isLocalRequest
* @param {URL to test} url
* @returns {bool} Whether the URL is local or not
* Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js
*/
isLocalRequest: function(url){
var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
urlLower = url.toLowerCase(),
parts = rurl.exec( urlLower ),
ajaxLocation,
ajaxLocParts;
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement('a');
ajaxLocation.href = '';
ajaxLocation = ajaxLocation.href;
}
ajaxLocation = ajaxLocation.toLowerCase();
// uh oh, the url must be relative
// make it fully qualified and re-regex url
if (!parts){
urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase();
parts = rurl.exec( urlLower );
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation ) || [];
// do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain)
var matched = !(parts &&
(parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
(parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !==
(ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443'))));
return matched;
},
/**
* Utility method to determine whether or not the argument passed in is or is not a native dom node.
* @method isNativeDOMNode
* @param {object} testObject The object you want to check as native dom node.
* @return {bool} Returns true if the object passed is a native dom node.
*/
isNativeDOMNode: function(testObject) {
var bIsNode = (
typeof Node === 'object' ? testObject instanceof Node :
testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string'
);
var bIsElement = (
typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2
testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string'
);
return (bIsNode || bIsElement);
},
/**
* A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console).
* @method log
* @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api).
* @param {object} [obj2]* An object to be logged
* @example
//Pass any object (string, int, array, object, bool) to .log()
F2.log('foo');
F2.log(myArray);
//Use a console method name as the first argument.
F2.log('error', err);
F2.log('info', 'The session ID is ' + sessionId);
* Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js)
*/
log: function() {
var _log;
var _logMethod = 'log';
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
var args;
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
//if first arg is a console function, use it.
//defaults to console.log()
if (arguments && arguments.length > 1 && arguments[0] == method){
_logMethod = method;
//remove console func from args
args = Array.prototype.slice.call(arguments, 1);
}
}
if (Function.prototype.bind) {
_log = Function.prototype.bind.call(console[_logMethod], console);
} else {
_log = function() {
Function.prototype.apply.call(console[_logMethod], console, (args || arguments));
};
}
_log.apply(this, (args || arguments));
},
/**
* Wrapper to convert a JSON string to an object
* @method parse
* @param {string} str The JSON string to convert
* @return {object} The parsed object
*/
parse: function(str) {
return JSON.parse(str);
},
/**
* Wrapper to convert an object to JSON
*
* **Note: When using F2.stringify on an F2.AppConfig object, it is
* recommended to pass F2.appConfigReplacer as the replacer function in
* order to prevent circular serialization errors.**
* @method stringify
* @param {object} value The object to convert
* @param {function|Array} replacer An optional parameter that determines
* how object values are stringified for objects. It can be a function or an
* array of strings.
* @param {int|string} space An optional parameter that specifies the
* indentation of nested structures. If it is omitted, the text will be
* packed without extra whitespace. If it is a number, it will specify the
* number of spaces to indent at each level. If it is a string (such as '\t'
* or ' '), it contains the characters used to indent at each level.
* @return {string} The JSON string
*/
stringify: function(value, replacer, space) {
return JSON.stringify(value, replacer, space);
},
/**
* Function to get the F2 version number
* @method version
* @return {string} F2 version number
*/
version: function() { return '1.3.3'; }
};
})();
/**
* The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction.
*
*<p class="alert alert-block alert-warning">
*The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated—but not removed—in version 1.2. They will be permanently removed in a future version of F2.
*</p>
*
*<p class="alert alert-block alert-info">
*Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout.
*</p>
*
* ### Order of Execution
*
* **App Rendering**
*
* 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed.
* 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached.
* 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached.
* 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired.
* 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached.
* 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached.
*
*
* **App Removal**
* 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run.
* 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached.
* 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached.
* 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached.
*
* **Error Handling**
* 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached.
*
* @class F2.AppHandlers
*/
F2.extend('AppHandlers', (function() {
// the hidden token that we will check against every time someone tries to add, remove, fire handler
var _ct = F2.guid();
var _f2t = F2.guid();
var _handlerCollection = {
appCreateRoot: [],
appRenderBefore: [],
appDestroyBefore: [],
appRenderAfter: [],
appDestroyAfter: [],
appRender: [],
appDestroy: [],
appScriptLoadFailed: []
};
var _defaultMethods = {
appRender: function(appConfig, appHtml)
{
var $root = null;
// if no app root is defined use the app's outer most node
if(!F2.isNativeDOMNode(appConfig.root))
{
appConfig.root = jQuery(appHtml).get(0);
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
}
else
{
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
// append the app html to the root
$root.append(appHtml);
}
// append the root to the body by default.
jQuery('body').append($root);
},
appDestroy: function(appInstance)
{
// call the apps destroy method, if it has one
if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
{
appInstance.app.destroy();
}
// warn the Container and App Developer that even though they have a destroy method it hasn't been
else if(appInstance && appInstance.app && appInstance.app.destroy)
{
F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
}
// fade out and remove the root
jQuery(appInstance.config.root).fadeOut(500, function() {
jQuery(this).remove();
});
}
};
var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(token);
// create handler structure. Not all arguments properties will be populated/used.
var handler = {
func: (typeof(func_or_element)) ? func_or_element : null,
namespace: sNamespace,
domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null
};
if(!handler.func && !handler.domNode)
{
throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.');
}
if(handler.domNode && !bDomNodeAppropriate)
{
throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.');
}
return handler;
};
var _validateToken = function(sToken)
{
// check token against F2 and container
if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); }
};
var _removeHandler = function(sToken, eventKey, sNamespace)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(sToken);
if(!sNamespace && !eventKey)
{
return;
}
// remove by event key
else if(!sNamespace && eventKey)
{
_handlerCollection[eventKey] = [];
}
// remove by namespace only
else if(sNamespace && !eventKey)
{
sNamespace = sNamespace.toLowerCase();
for(var currentEventKey in _handlerCollection)
{
var eventCollection = _handlerCollection[currentEventKey];
var newEvents = [];
for(var i = 0, ec = eventCollection.length; i < ec; i++)
{
var currentEventHandler = eventCollection[i];
if(currentEventHandler)
{
if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace)
{
newEvents.push(currentEventHandler);
}
}
}
eventCollection = newEvents;
}
}
else if(sNamespace && _handlerCollection[eventKey])
{
sNamespace = sNamespace.toLowerCase();
var newHandlerCollection = [];
for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++)
{
var currentHandler = _handlerCollection[eventKey][iCounter];
if(currentHandler)
{
if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace)
{
newHandlerCollection.push(currentHandler);
}
}
}
_handlerCollection[eventKey] = newHandlerCollection;
}
};
return {
/**
* Allows Container Developer to retrieve a unique token which must be passed to
* all `on` and `off` methods. This function will self destruct and can only be called
* one time. Container Developers must store the return value inside of a closure.
* @method getToken
**/
getToken: function()
{
// delete this method for security that way only the container has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.getToken;
// return the token, which we validate against.
return _ct;
},
/**
* Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}.
* This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}
* and additional internal methods.
* @method __f2GetToken
* @private
**/
__f2GetToken: function()
{
// delete this method for security that way only the F2 internally has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.__f2GetToken;
// return the token, which we validate against.
return _f2t;
},
/**
* Allows F2 to trigger specific events internally.
* @method __trigger
* @private
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}.
* @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
**/
__trigger: function(token, eventKey) // additional arguments will likely be passed
{
// will throw an exception and stop execution if the token is invalid
if(token != _f2t)
{
throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().');
}
if(_handlerCollection && _handlerCollection[eventKey])
{
// create a collection of arguments that are safe to pass to the callback.
var passableArgs = [];
// populate that collection with all arguments except token and eventKey
for(var i = 2, j = arguments.length; i < j; i++)
{
passableArgs.push(arguments[i]);
}
if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey])
{
_defaultMethods[eventKey].apply(F2, passableArgs);
return this;
}
else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey])
{
return this;
}
// fire all event listeners in the order that they were added.
for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++)
{
var handler = _handlerCollection[eventKey][iCounter];
// appRender where root is already defined
if (handler.domNode && arguments[2] && arguments[2].root && arguments[3])
{
var $appRoot = jQuery(arguments[2].root).append(arguments[3]);
jQuery(handler.domNode).append($appRoot);
}
else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3])
{
// set the root to the actual HTML of the app
arguments[2].root = jQuery(arguments[3]).get(0);
// appends the root to the dom node specified
jQuery(handler.domNode).append(arguments[2].root);
}
else
{
handler.func.apply(F2, passableArgs);
}
}
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {HTMLElement} element Specific DOM element to which app gets appended.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRender',
* document.getElementById('my_app')
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRender.myNamespace',
* document.getElementById('my_app')
* );
**/
/**
* Allows Container Developer to add listener method that will be triggered when a specific event occurs.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore'
* function() { F2.log('before app rendered!'); }
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore.myNamespace',
* function() { F2.log('before app rendered!'); }
* );
**/
on: function(token, eventKey, func_or_element)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_handlerCollection[eventKey].push(
_createHandler(
token,
sNamespace,
func_or_element,
(eventKey == 'appRender')
)
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to remove listener methods for specific events
* @method off
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all
* listeners for the specified event type will be removed.
* Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.off(_token,'appRenderBefore');
*
**/
off: function(token, eventKey)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_removeHandler(
token,
eventKey,
sNamespace
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
}
};
})());
F2.extend('Constants', {
/**
* A convenient collection of all available appHandler events.
* @class F2.Constants.AppHandlers
**/
AppHandlers: (function()
{
return {
/**
* Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_CREATE_ROOT
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_CREATE_ROOT,
* function(appConfig)
* {
* // If you want to create a custom root. By default F2 uses the app's outermost HTML element.
* // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER
* appConfig.root = jQuery('<section></section>').get(0);
* }
* );
*/
APP_CREATE_ROOT: 'appCreateRoot',
/**
* Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_BEFORE,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_BEFORE: 'appRenderBefore',
/**
* Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) )
* @property APP_RENDER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER,
* function(appConfig, appHtml)
* {
* var $root = null;
*
* // if no app root is defined use the app's outer most node
* if(!F2.isNativeDOMNode(appConfig.root))
* {
* appConfig.root = jQuery(appHtml).get(0);
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
* }
* else
* {
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
*
* // append the app html to the root
* $root.append(appHtml);
* }
*
* // append the root to the body by default.
* jQuery('body').append($root);
* }
* );
*/
APP_RENDER: 'appRender',
/**
* Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_AFTER,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_AFTER: 'appRenderAfter',
/**
* Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_BEFORE: 'appDestroyBefore',
/**
* Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY,
* function(appInstance)
* {
* // call the apps destroy method, if it has one
* if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
* {
* appInstance.app.destroy();
* }
* else if(appInstance && appInstance.app && appInstance.app.destroy)
* {
* F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
* }
*
* // fade out and remove the root
* jQuery(appInstance.config.root).fadeOut(500, function() {
* jQuery(this).remove();
* });
* }
* );
*/
APP_DESTROY: 'appDestroy',
/**
* Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_AFTER,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_AFTER: 'appDestroyAfter',
/**
* Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo )
* @property APP_SCRIPT_LOAD_FAILED
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
* function(appConfig, scriptInfo)
* {
* F2.log(appConfig.appId);
* }
* );
*/
APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed'
};
})()
});
/**
* Class stubs for documentation purposes
* @main F2
*/
F2.extend('', {
/**
* The App Class is an optional class that can be namespaced onto the
* {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The
* [F2 Docs](../../app-development.html#app-class)
* has more information on the usage of the App Class.
* @class F2.App
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object for the app
* @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent
* object
* @param {Element} root The root DOM Element for the app
*/
App: function(appConfig, appContent, root) {
return {
/**
* An optional init function that will automatically be called when
* F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called.
* @method init
* @optional
*/
init:function() {}
};
},
/**
* The AppConfig object represents an app's meta data
* @class F2.AppConfig
*/
AppConfig: {
/**
* The unique ID of the app. More information can be found
* [here](../../app-development.html#f2-appid)
* @property appId
* @type string
* @required
*/
appId: '',
/**
* An object that represents the context of an app
* @property context
* @type object
*/
context: {},
/**
* True if the app should be requested in a single request with other apps.
* @property enableBatchRequests
* @type bool
* @default false
*/
enableBatchRequests: false,
/**
* The height of the app. The initial height will be pulled from
* the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later
* modified by calling
* F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used
* for secure apps to be able to set the initial height of the iframe.
* @property height
* @type int
*/
height: 0,
/**
* The unique runtime ID of the app.
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property instanceId
* @type string
*/
instanceId: '',
/**
* True if the app will be loaded in an iframe. This property
* will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object
* sets isSecure = true. It will also be true if the
* [container](../../container-development.html) has made the decision to
* run apps in iframes.
* @property isSecure
* @type bool
* @default false
*/
isSecure: false,
/**
* The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* object.
* @property manifestUrl
* @type string
* @required
*/
manifestUrl: '',
/**
* The recommended maximum width in pixels that this app should be run.
* **It is up to the [container](../../container-development.html) to
* implement the logic to prevent an app from being run when the maxWidth
* requirements are not met.**
* @property maxWidth
* @type int
*/
maxWidth: 0,
/**
* The recommended minimum grid size that this app should be run. This
* value corresponds to the 12-grid system that is used by the
* [container](../../container-development.html). This property should be
* set by apps that require a certain number of columns in their layout.
* @property minGridSize
* @type int
* @default 4
*/
minGridSize: 4,
/**
* The recommended minimum width in pixels that this app should be run. **It
* is up to the [container](../../container-development.html) to implement
* the logic to prevent an app from being run when the minWidth requirements
* are not met.
* @property minWidth
* @type int
* @default 300
*/
minWidth: 300,
/**
* The name of the app
* @property name
* @type string
* @required
*/
name: '',
/**
* The root DOM element that contains the app
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property root
* @type Element
*/
root: undefined,
/**
* The instance of F2.UI providing easy access to F2.UI methods
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property ui
* @type F2.UI
*/
ui: undefined,
/**
* The views that this app supports. Available views
* are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The
* presence of a view can be checked via
* F2.{{#crossLink "F2/inArray"}}{{/crossLink}}:
*
* F2.inArray(F2.Constants.Views.SETTINGS, app.views)
*
* @property views
* @type Array
*/
views: []
},
/**
* The assets needed to render an app on the page
* @class F2.AppManifest
*/
AppManifest: {
/**
* The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}}
* objects
* @property apps
* @type Array
* @required
*/
apps: [],
/**
* Any inline javascript tha should initially be run
* @property inlineScripts
* @type Array
* @optional
*/
inlineScripts: [],
/**
* Urls to javascript files required by the app
* @property scripts
* @type Array
* @optional
*/
scripts: [],
/**
* Urls to CSS files required by the app
* @property styles
* @type Array
* @optional
*/
styles: []
},
/**
* The AppContent object
* @class F2.AppManifest.AppContent
**/
AppContent: {
/**
* Arbitrary data to be passed along with the app
* @property data
* @type object
* @optional
*/
data: {},
/**
* The string of HTML representing the app
* @property html
* @type string
* @required
*/
html: '',
/**
* A status message
* @property status
* @type string
* @optional
*/
status: ''
},
/**
* An object containing configuration information for the
* [container](../../container-development.html)
* @class F2.ContainerConfig
*/
ContainerConfig: {
/**
* Allows the [container](../../container-development.html) to override how
* an app's html is inserted into the page. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html
* @method afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
* @return {Element} The DOM Element surrounding the app
*/
afterAppRender: function(appConfig, html) {},
/**
* Allows the [container](../../container-development.html) to wrap an app
* in extra html. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html. The extra html can provide links to edit app settings and remove an
* app from the container. See
* {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that
* should be applied to elements.
* @method appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
*/
appRender: function(appConfig, html) {},
/**
* Allows the container to render html for an app before the AppManifest for
* an app has loaded. This can be useful if the design calls for loading
* icons to appear for each app before each app is loaded and rendered to
* the page.
* @method beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
beforeAppRender: function(appConfig) {},
/**
* True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc.
* @property debugMode
* @type bool
* @default false
*/
debugMode: false,
/**
* Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire.
* @property scriptErrorTimeout
* @type milliseconds
* @default 7000 (7 seconds)
*/
scriptErrorTimeout: 7000,
/**
* Tells the container that it is currently running within
* a secure app page
* @property isSecureAppPage
* @type bool
*/
isSecureAppPage: false,
/**
* Allows the container to specify which page is used when
* loading a secure app. The page must reside on a different domain than the
* container
* @property secureAppPagePath
* @type string
* @for F2.ContainerConfig
*/
secureAppPagePath: '',
/**
* Specifies what views a container will provide buttons
* or links to. Generally, the views will be switched via buttons or links
* in the app's header.
* @property supportedViews
* @type Array
* @required
*/
supportedViews: [],
/**
* An object containing configuration defaults for F2.UI
* @class F2.ContainerConfig.UI
*/
UI: {
/**
* An object containing configuration defaults for the
* F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and
* F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods.
* @class F2.ContainerConfig.UI.Mask
*/
Mask: {
/**
* The backround color of the overlay
* @property backgroundColor
* @type string
* @default #FFF
*/
backgroundColor: '#FFF',
/**
* The path to the loading icon
* @property loadingIcon
* @type string
*/
loadingIcon: '',
/**
* The opacity of the background overlay
* @property opacity
* @type int
* @default 0.6
*/
opacity: 0.6,
/**
* Do not use inline styles for mask functinality. Instead classes will
* be applied to the elements and it is up to the container provider to
* implement the class definitions.
* @property useClasses
* @type bool
* @default false
*/
useClasses: false,
/**
* The z-index to use for the overlay
* @property zIndex
* @type int
* @default 2
*/
zIndex: 2
}
},
/**
* Allows the container to fully override how the AppManifest request is
* made inside of F2.
*
* @method xhr
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {function} success The function to be called if the request
* succeeds
* @param {function} error The function to be called if the request fails
* @param {function} complete The function to be called when the request
* finishes (after success and error callbacks have been executed)
* @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has
* an `abort` function (such as the jqXHR object in jQuery) to abort the
* request)
*
* @example
* F2.init({
* xhr: function(url, appConfigs, success, error, complete) {
* $.ajax({
* url: url,
* type: 'POST',
* data: {
* params: F2.stringify(appConfigs, F2.appConfigReplacer)
* },
* jsonp: false, // do not put 'callback=' in the query string
* jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name
* dataType: 'json',
* success: function(appManifest) {
* // custom success logic
* success(appManifest); // fire success callback
* },
* error: function() {
* // custom error logic
* error(); // fire error callback
* },
* complete: function() {
* // custom complete logic
* complete(); // fire complete callback
* }
* });
* }
* });
*
* @for F2.ContainerConfig
*/
//xhr: function(url, appConfigs, success, error, complete) {},
/**
* Allows the container to override individual parts of the AppManifest
* request. See properties and methods with the `xhr.` prefix.
* @property xhr
* @type Object
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
xhr: {
/**
* Allows the container to override the request data type (JSON or JSONP)
* that is used for the request
* @method xhr.dataType
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request data type that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
dataType: function(url, appConfigs) {},
/**
* Allows the container to override the request method that is used (just
* like the `type` parameter to `jQuery.ajax()`.
* @method xhr.type
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request method that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
type: function(url, appConfigs) {},
/**
* Allows the container to override the url that is used to request an
* app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}}
* @method xhr.url
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The url that should be used for the request
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
url: function(url, appConfigs) {}
},
/**
* Allows the container to override the script loader which requests
* dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}.
* @property loadScripts
* @type function
*
* @example
* F2.init({
* loadScripts: function(scripts,inlines,callback){
* //load scripts using $.load() for each script or require(scripts)
* callback();
* }
* });
*/
loadScripts: function(scripts,inlines,callback){},
/**
* Allows the container to override the stylesheet loader which requests
* dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}.
* @property loadStyles
* @type function
*
* @example
* F2.init({
* loadStyles: function(styles,callback){
* //load styles using $.load() for each stylesheet or another method
* callback();
* }
* });
*/
loadStyles: function(styles,callback){}
}
});
/**
* Constants used throughout the Open Financial Framework
* @class F2.Constants
* @static
*/
F2.extend('Constants', {
/**
* CSS class constants
* @class F2.Constants.Css
*/
Css: (function() {
/** @private */
var _PREFIX = 'f2-';
return {
/**
* The APP class should be applied to the DOM Element that surrounds the
* entire app, including any extra html that surrounds the APP\_CONTAINER
* that is inserted by the container. See the
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object.
* @property APP
* @type string
* @static
* @final
*/
APP: _PREFIX + 'app',
/**
* The APP\_CONTAINER class should be applied to the outermost DOM Element
* of the app.
* @property APP_CONTAINER
* @type string
* @static
* @final
*/
APP_CONTAINER: _PREFIX + 'app-container',
/**
* The APP\_TITLE class should be applied to the DOM Element that contains
* the title for an app. If this class is not present, then
* F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function.
* @property APP_TITLE
* @type string
* @static
* @final
*/
APP_TITLE: _PREFIX + 'app-title',
/**
* The APP\_VIEW class should be applied to the DOM Element that contains
* a view for an app. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is.
* @property APP_VIEW
* @type string
* @static
* @final
*/
APP_VIEW: _PREFIX + 'app-view',
/**
* APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that
* trigger an
* {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE
* event. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger.
* @property APP_VIEW_TRIGGER
* @type string
* @static
* @final
*/
APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger',
/**
* The MASK class is applied to the overlay element that is created
* when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is
* fired.
* @property MASK
* @type string
* @static
* @final
*/
MASK: _PREFIX + 'mask',
/**
* The MASK_CONTAINER class is applied to the Element that is passed into
* the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method.
* @property MASK_CONTAINER
* @type string
* @static
* @final
*/
MASK_CONTAINER: _PREFIX + 'mask-container'
};
})(),
/**
* Events constants
* @class F2.Constants.Events
*/
Events: (function() {
/** @private */
var _APP_EVENT_PREFIX = 'App.';
/** @private */
var _CONTAINER_EVENT_PREFIX = 'Container.';
return {
/**
* The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an
* app. It is up to the app developer to fire this event.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property APP_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange',
/**
* The APP\_WIDTH\_CHANGE event will be fired by the container when the
* width of an app is changed. The app's instanceId should be concatenated
* to this constant.
* Returns an object with the gridSize and width in pixels:
*
* { gridSize:8, width:620 }
*
* @property APP_WIDTH_CHANGE
* @type string
* @static
* @final
*/
APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.',
/**
* The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed
* at the container level. This event should only be fired by the
* container or container provider.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property CONTAINER_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange',
/**
* The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when
* the width of the container has changed.
* @property CONTAINER_WIDTH_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange'
};
})(),
JSONP_CALLBACK: 'F2_jsonpCallback_',
/**
* Constants for use with cross-domain sockets
* @class F2.Constants.Sockets
* @protected
*/
Sockets: {
/**
* The EVENT message is sent whenever
* F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired
* @property EVENT
* @type string
* @static
* @final
*/
EVENT: '__event__',
/**
* The LOAD message is sent when an iframe socket initially loads.
* Returns a JSON string that represents:
*
* [ App, AppManifest]
*
* @property LOAD
* @type string
* @static
* @final
*/
LOAD: '__socketLoad__',
/**
* The RPC message is sent when a method is passed up from within a secure
* app page.
* @property RPC
* @type string
* @static
* @final
*/
RPC: '__rpc__',
/**
* The RPC\_CALLBACK message is sent when a call back from an RPC method is
* fired.
* @property RPC_CALLBACK
* @type string
* @static
* @final
*/
RPC_CALLBACK: '__rpcCallback__',
/**
* The UI\_RPC message is sent when a UI method called.
* @property UI_RPC
* @type string
* @static
* @final
*/
UI_RPC: '__uiRpc__'
},
/**
* The available view types to apps. The view should be specified by applying
* the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the
* containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the
* Element as well which defines what view type is represented.
* The `hide` class can be applied to views that should be hidden by default.
* @class F2.Constants.Views
*/
Views: {
/**
* The DATA_ATTRIBUTE should be placed on the DOM Element that contains the
* view.
* @property DATA_ATTRIBUTE
* @type string
* @static
* @final
*/
DATA_ATTRIBUTE: 'data-f2-view',
/**
* The ABOUT view gives details about the app.
* @property ABOUT
* @type string
* @static
* @final
*/
ABOUT: 'about',
/**
* The HELP view provides users with help information for using an app.
* @property HELP
* @type string
* @static
* @final
*/
HELP: 'help',
/**
* The HOME view is the main view for an app. This view should always
* be provided by an app.
* @property HOME
* @type string
* @static
* @final
*/
HOME: 'home',
/**
* The REMOVE view is a special view that handles the removal of an app
* from the container.
* @property REMOVE
* @type string
* @static
* @final
*/
REMOVE: 'remove',
/**
* The SETTINGS view provides users the ability to modify advanced settings
* for an app.
* @property SETTINGS
* @type string
* @static
* @final
*/
SETTINGS: 'settings'
}
});
/**
* Handles [Context](../../app-development.html#context) passing from
* containers to apps and apps to apps.
* @class F2.Events
*/
F2.extend('Events', (function() {
// init EventEmitter
var _events = new EventEmitter2({
wildcard:true
});
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
return {
/**
* Same as F2.Events.emit except that it will not send the event
* to all sockets.
* @method _socketEmit
* @private
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
_socketEmit: function() {
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Execute each of the listeners that may be listening for the specified
* event name in order with the list of arguments.
* @method emit
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
emit: function() {
F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments));
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Adds a listener that will execute n times for the event before being
* removed. The listener is invoked only the first time the event is
* fired, after which it is removed.
* @method many
* @param {string} event The event name
* @param {int} timesToListen The number of times to execute the event
* before being removed
* @param {function} listener The function to be fired when the event is
* emitted
*/
many: function(event, timesToListen, listener) {
return _events.many(event, timesToListen, listener);
},
/**
* Remove a listener for the specified event.
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
*/
off: function(event, listener) {
return _events.off(event, listener);
},
/**
* Adds a listener for the specified event
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
on: function(event, listener){
return _events.on(event, listener);
},
/**
* Adds a one time listener for the event. The listener is invoked only
* the first time the event is fired, after which it is removed.
* @method once
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
once: function(event, listener) {
return _events.once(event, listener);
}
};
})());
/**
* Handles socket communication between the container and secure apps
* @class F2.Rpc
*/
F2.extend('Rpc', (function(){
var _callbacks = {};
var _secureAppPagePath = '';
var _apps = {};
var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT);
var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC);
var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK);
var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD);
var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC);
/**
* Creates a socket connection from the app to the container using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createAppToContainerSocket
* @private
*/
var _createAppToContainerSocket = function() {
var appConfig; // socket closure
var isLoaded = false;
// its possible for messages to be received before the socket load event has
// happened. We'll save off these messages and replay them once the socket
// is ready
var messagePlayback = [];
var socket = new easyXDM.Socket({
onMessage: function(message, origin){
// handle Socket Load
if (!isLoaded && _rSocketLoad.test(message)) {
message = message.replace(_rSocketLoad, '');
var appParts = F2.parse(message);
// make sure we have the AppConfig and AppManifest
if (appParts.length == 2) {
appConfig = appParts[0];
// save socket
_apps[appConfig.instanceId] = {
config:appConfig,
socket:socket
};
// register app
F2.registerApps([appConfig], [appParts[1]]);
// socket message playback
jQuery.each(messagePlayback, function(i, e) {
_onMessage(appConfig, message, origin);
});
isLoaded = true;
}
} else if (isLoaded) {
// pass everyting else to _onMessage
_onMessage(appConfig, message, origin);
} else {
//F2.log('socket not ready, queuing message', message);
messagePlayback.push(message);
}
}
});
};
/**
* Creates a socket connection from the container to the app using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createContainerToAppSocket
* @private
* @param {appConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The F2.AppManifest object
*/
var _createContainerToAppSocket = function(appConfig, appManifest) {
var container = jQuery(appConfig.root);
if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) {
container.find('.' + F2.Constants.Css.APP_CONTAINER);
}
if (!container.length) {
F2.log('Unable to locate app in order to establish secure connection.');
return;
}
var iframeProps = {
scrolling:'no',
style:{
width:'100%'
}
};
if (appConfig.height) {
iframeProps.style.height = appConfig.height + 'px';
}
var socket = new easyXDM.Socket({
remote: _secureAppPagePath,
container: container.get(0),
props:iframeProps,
onMessage: function(message, origin) {
// pass everything to _onMessage
_onMessage(appConfig, message, origin);
},
onReady: function() {
socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer));
}
});
return socket;
};
/**
* @method _createRpcCallback
* @private
* @param {string} instanceId The app's Instance ID
* @param {function} callbackId The callback ID
* @return {function} A function to make the RPC call
*/
var _createRpcCallback = function(instanceId, callbackId) {
return function() {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC_CALLBACK,
callbackId,
[].slice.call(arguments).slice(2)
);
};
};
/**
* Handles messages that come across the sockets
* @method _onMessage
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} message The socket message
* @param {string} origin The originator
*/
var _onMessage = function(appConfig, message, origin) {
var obj, func;
function parseFunction(parent, functionName) {
var path = String(functionName).split('.');
for (var i = 0; i < path.length; i++) {
if (parent[path[i]] === undefined) {
parent = undefined;
break;
}
parent = parent[path[i]];
}
return parent;
}
function parseMessage(regEx, message, instanceId) {
var o = F2.parse(message.replace(regEx, ''));
// if obj.callbacks
// for each callback
// for each params
// if callback matches param
// replace param with _createRpcCallback(app.instanceId, callback)
if (o.params && o.params.length && o.callbacks && o.callbacks.length) {
jQuery.each(o.callbacks, function(i, c) {
jQuery.each(o.params, function(i, p) {
if (c == p) {
o.params[i] = _createRpcCallback(instanceId, c);
}
});
});
}
return o;
}
// handle UI Call
if (_rUiCall.test(message)) {
obj = parseMessage(_rUiCall, message, appConfig.instanceId);
func = parseFunction(appConfig.ui, obj.functionName);
// if we found the function, call it
if (func !== undefined) {
func.apply(appConfig.ui, obj.params);
} else {
F2.log('Unable to locate UI RPC function: ' + obj.functionName);
}
// handle RPC
} else if (_rRpc.test(message)) {
obj = parseMessage(_rRpc, message, appConfig.instanceId);
func = parseFunction(window, obj.functionName);
if (func !== undefined) {
func.apply(func, obj.params);
} else {
F2.log('Unable to locate RPC function: ' + obj.functionName);
}
// handle RPC Callback
} else if (_rRpcCallback.test(message)) {
obj = parseMessage(_rRpcCallback, message, appConfig.instanceId);
if (_callbacks[obj.functionName] !== undefined) {
_callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params);
delete _callbacks[obj.functionName];
}
// handle Events
} else if (_rEvents.test(message)) {
obj = parseMessage(_rEvents, message, appConfig.instanceId);
F2.Events._socketEmit.apply(F2.Events, obj);
}
};
/**
* Registers a callback function
* @method _registerCallback
* @private
* @param {function} callback The callback function
* @return {string} The callback ID
*/
var _registerCallback = function(callback) {
var callbackId = F2.guid();
_callbacks[callbackId] = callback;
return callbackId;
};
return {
/**
* Broadcast an RPC function to all sockets
* @method broadcast
* @param {string} messageType The message type
* @param {Array} params The parameters to broadcast
*/
broadcast: function(messageType, params) {
// check valid messageType
var message = messageType + F2.stringify(params);
jQuery.each(_apps, function(i, a) {
a.socket.postMessage(message);
});
},
/**
* Calls a remote function
* @method call
* @param {string} instanceId The app's Instance ID
* @param {string} messageType The message type
* @param {string} functionName The name of the remote function
* @param {Array} params An array of parameters to pass to the remote
* function. Any functions found within the params will be treated as a
* callback function.
*/
call: function(instanceId, messageType, functionName, params) {
// loop through params and find functions and convert them to callbacks
var callbacks = [];
jQuery.each(params, function(i, e) {
if (typeof e === 'function') {
var cid = _registerCallback(e);
params[i] = cid;
callbacks.push(cid);
}
});
// check valid messageType
_apps[instanceId].socket.postMessage(
messageType + F2.stringify({
functionName:functionName,
params:params,
callbacks:callbacks
})
);
},
/**
* Init function which tells F2.Rpc whether it is running at the container-
* level or the app-level. This method is generally called by
* F2.{{#crossLink "F2/init"}}{{/crossLink}}
* @method init
* @param {string} [secureAppPagePath] The
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath
* property
*/
init: function(secureAppPagePath) {
_secureAppPagePath = secureAppPagePath;
if (!_secureAppPagePath) {
_createAppToContainerSocket();
}
},
/**
* Determines whether the Instance ID is considered to be 'remote'. This is
* determined by checking if 1) the app has an open socket and 2) whether
* F2.Rpc is running inside of an iframe
* @method isRemote
* @param {string} instanceId The Instance ID
* @return {bool} True if there is an open socket
*/
isRemote: function(instanceId) {
return (
// we have an app
_apps[instanceId] !== undefined &&
// the app is secure
_apps[instanceId].config.isSecure &&
// we can't access the iframe
jQuery(_apps[instanceId].config.root).find('iframe').length === 0
);
},
/**
* Creates a container-to-app or app-to-container socket for communication
* @method register
* @param {F2.AppConfig} [appConfig] The F2.AppConfig object
* @param {F2.AppManifest} [appManifest] The F2.AppManifest object
*/
register: function(appConfig, appManifest) {
if (!!appConfig && !!appManifest) {
_apps[appConfig.instanceId] = {
config:appConfig,
socket:_createContainerToAppSocket(appConfig, appManifest)
};
} else {
F2.log('Unable to register socket connection. Please check container configuration.');
}
}
};
})());
F2.extend('UI', (function(){
var _containerConfig;
/**
* UI helper methods
* @class F2.UI
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object
*/
var UI_Class = function(appConfig) {
var _appConfig = appConfig;
var $root = jQuery(appConfig.root);
var _updateHeight = function(height) {
height = height || jQuery(_appConfig.root).outerHeight();
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'updateHeight',
[
height
]
);
} else {
_appConfig.height = height;
$root.find('iframe').height(_appConfig.height);
}
};
return {
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
*/
hideMask: function(selector) {
F2.UI.hideMask(_appConfig.instanceId, selector);
},
/**
* Helper methods for creating and using Modals
* @class F2.UI.Modals
* @for F2.UI
*/
Modals: (function(){
var _renderAlert = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Alert!</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button class="btn btn-primary btn-ok">OK</button>',
'</div>',
'</div>'
].join('');
};
var _renderConfirm = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Confirm</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button type="button" class="btn btn-primary btn-ok">OK</button>',
'<button type="button" class="btn btn-cancel">Cancel</button">',
'</div>',
'</div>'
].join('');
};
return {
/**
* Display an alert message on the page
* @method alert
* @param {string} message The message to be displayed
* @param {function} [callback] The callback to be fired when the user
* closes the dialog
* @for F2.UI.Modals
*/
alert: function(message, callback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.alert()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.alert',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderAlert(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-primary').on('click', function() {
jQuery(modal).modal('hide').remove();
(callback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
},
/**
* Display a confirm message on the page
* @method confirm
* @param {string} message The message to be displayed
* @param {function} okCallback The function that will be called when the OK
* button is pressed
* @param {function} cancelCallback The function that will be called when
* the Cancel button is pressed
* @for F2.UI.Modals
*/
confirm: function(message, okCallback, cancelCallback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.confirm()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.confirm',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderConfirm(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-ok').on('click', function() {
jQuery(modal).modal('hide').remove();
(okCallback || jQuery.noop)();
});
jQuery(modal).find('.btn-cancel').on('click', function() {
jQuery(modal).modal('hide').remove();
(cancelCallback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
}
};
})(),
/**
* Sets the title of the app as shown in the browser. Depending on the
* container HTML, this method may do nothing if the container has not been
* configured properly or else the container provider does not allow Title's
* to be set.
* @method setTitle
* @params {string} title The title of the app
* @for F2.UI
*/
setTitle: function(title) {
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'setTitle',
[
title
]
);
} else {
jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title);
}
},
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
showMask: function(selector, showLoader) {
F2.UI.showMask(_appConfig.instanceId, selector, showLoader);
},
/**
* For secure apps, this method updates the size of the iframe that
* contains the app. **Note: It is recommended that app developers call
* this method anytime Elements are added or removed from the DOM**
* @method updateHeight
* @params {int} height The height of the app
*/
updateHeight: _updateHeight,
/**
* Helper methods for creating and using Views
* @class F2.UI.Views
* @for F2.UI
*/
Views: (function(){
var _events = new EventEmitter2();
var _rValidEvents = /change/i;
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
var _isValid = function(eventName) {
if (_rValidEvents.test(eventName)) {
return true;
} else {
F2.log('"' + eventName + '" is not a valid F2.UI.Views event name');
return false;
}
};
return {
/**
* Change the current view for the app or add an event listener
* @method change
* @param {string|function} [input] If a string is passed in, the view
* will be changed for the app. If a function is passed in, a change
* event listener will be added.
* @for F2.UI.Views
*/
change: function(input) {
if (typeof input === 'function') {
this.on('change', input);
} else if (typeof input === 'string') {
if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Views.change',
[].slice.call(arguments)
);
} else if (F2.inArray(input, _appConfig.views)) {
jQuery('.' + F2.Constants.Css.APP_VIEW, $root)
.addClass('hide')
.filter('[data-f2-view="' + input + '"]', $root)
.removeClass('hide');
_updateHeight();
_events.emit('change', input);
}
}
},
/**
* Removes a view event listener
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
* @for F2.UI.Views
*/
off: function(event, listener) {
if (_isValid(event)) {
_events.off(event, listener);
}
},
/**
* Adds a view event listener
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
* @for F2.UI.Views
*/
on: function(event, listener) {
if (_isValid(event)) {
_events.on(event, listener);
}
}
};
})()
};
};
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
* @for F2.UI
*/
UI_Class.hideMask = function(instanceId, selector) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.hideMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.hideMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector
]
);
} else {
var container = jQuery(selector);
container.find('> .' + F2.Constants.Css.MASK).remove();
container.removeClass(F2.Constants.Css.MASK_CONTAINER);
// if the element contains this data property, we need to reset static
// position
if (container.data(F2.Constants.Css.MASK_CONTAINER)) {
container.css({'position':'static'});
}
}
};
/**
*
* @method init
* @static
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
UI_Class.init = function(containerConfig) {
_containerConfig = containerConfig;
// set defaults
_containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {});
};
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
UI_Class.showMask = function(instanceId, selector, showLoading) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.showMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.showMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector,
showLoading
]
);
} else {
if (showLoading && !_containerConfig.UI.Mask.loadingIcon) {
F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();');
}
var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER);
var mask = jQuery('<div>')
.height('100%' /*container.outerHeight()*/)
.width('100%' /*container.outerWidth()*/)
.addClass(F2.Constants.Css.MASK);
// set inline styles if useClasses is false
if (!_containerConfig.UI.Mask.useClasses) {
mask.css({
'background-color':_containerConfig.UI.Mask.backgroundColor,
'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '',
'background-position':'50% 50%',
'background-repeat':'no-repeat',
'display':'block',
'left':0,
'min-height':30,
'padding':0,
'position':'absolute',
'top':0,
'z-index':_containerConfig.UI.Mask.zIndex,
'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')',
'opacity':_containerConfig.UI.Mask.opacity
});
}
// only set the position if the container is currently static
if (container.css('position') === 'static') {
container.css({'position':'relative'});
// setting this data property tells hideMask to set the position
// back to static
container.data(F2.Constants.Css.MASK_CONTAINER, true);
}
// add the mask to the container
container.append(mask);
}
};
return UI_Class;
})());
/**
* Root namespace of the F2 SDK
* @module f2
* @class F2
*/
F2.extend('', (function() {
var _apps = {};
var _config = false;
var _bUsesAppHandlers = false;
var _sAppHandlerToken = F2.AppHandlers.__f2GetToken();
/**
* Appends the app's html to the DOM
* @method _afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
* @return {Element} The DOM Element that contains the app
*/
var _afterAppRender = function(appConfig, html) {
var handler = _config.afterAppRender || function(appConfig, html) {
return jQuery(html).appendTo('body');
};
var appContainer = handler(appConfig, html);
if ( !! _config.afterAppRender && !appContainer) {
F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app');
return;
}
else {
// apply APP class and Instance ID
jQuery(appContainer).addClass(F2.Constants.Css.APP);
return appContainer.get(0);
}
};
/**
* Renders the html for an app.
* @method _appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
*/
var _appRender = function(appConfig, html) {
// apply APP_CONTAINER class
html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId));
// optionally apply wrapper html
if (_config.appRender) {
html = _config.appRender(appConfig, html);
}
// apply APP class and instanceId
return _outerHtml(html);
};
/**
* Rendering hook to allow containers to render some html prior to an app
* loading
* @method _beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
var _beforeAppRender = function(appConfig) {
var handler = _config.beforeAppRender || jQuery.noop;
return handler(appConfig);
};
/**
* Handler to inform the container that a script failed to load
* @method _onScriptLoadFailure
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param scriptInfo The path of the script that failed to load or the exception info
* for the inline script that failed to execute
*/
var _appScriptLoadFailed = function(appConfig, scriptInfo) {
var handler = _config.appScriptLoadFailed || jQuery.noop;
return handler(appConfig, scriptInfo);
};
/**
* Adds properties to the AppConfig object
* @method _createAppConfig
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with
* necessary properties
*/
var _createAppConfig = function(appConfig) {
// make a copy of the app config to ensure that the original is not modified
appConfig = jQuery.extend(true, {}, appConfig);
// create the instanceId for the app
appConfig.instanceId = appConfig.instanceId || F2.guid();
// default the views if not provided
appConfig.views = appConfig.views || [];
if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) {
appConfig.views.push(F2.Constants.Views.HOME);
}
return appConfig;
};
/**
* Adds properties to the ContainerConfig object to take advantage of defaults
* @method _hydrateContainerConfig
* @private
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
var _hydrateContainerConfig = function(containerConfig) {
if (!containerConfig.scriptErrorTimeout) {
containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout;
}
if (containerConfig.debugMode !== true) {
containerConfig.debugMode = F2.ContainerConfig.debugMode;
}
};
/**
* Attach app events
* @method _initAppEvents
* @private
*/
var _initAppEvents = function(appConfig) {
jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) {
event.preventDefault();
var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase();
// handle the special REMOVE view
if (view == F2.Constants.Views.REMOVE) {
F2.removeApp(appConfig.instanceId);
}
else {
appConfig.ui.Views.change(view);
}
});
};
/**
* Attach container Events
* @method _initContainerEvents
* @private
*/
var _initContainerEvents = function() {
var resizeTimeout;
var resizeHandler = function() {
F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE);
};
jQuery(window).on('resize', function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeHandler, 100);
});
};
/**
* Has the container been init?
* @method _isInit
* @private
* @return {bool} True if the container has been init
*/
var _isInit = function() {
return !!_config;
};
/**
* Instantiates each app from it's appConfig and stores that in a local private collection
* @method _createAppInstance
* @private
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
*/
var _createAppInstance = function(appConfig, appContent) {
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// instantiate F2.App
if (F2.Apps[appConfig.appId] !== undefined) {
if (typeof F2.Apps[appConfig.appId] === 'function') {
// IE
setTimeout(function() {
_apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root);
if (_apps[appConfig.instanceId].app['init'] !== undefined) {
_apps[appConfig.instanceId].app.init();
}
}, 0);
}
else {
F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')');
}
}
};
/**
* Loads the app's html/css/javascript
* @method loadApp
* @private
* @param {Array} appConfigs An array of
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
* @param {F2.AppManifest} [appManifest] The AppManifest object
*/
var _loadApps = function(appConfigs, appManifest) {
appConfigs = [].concat(appConfigs);
// check for secure app
if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) {
_loadSecureApp(appConfigs[0], appManifest);
return;
}
// check that the number of apps in manifest matches the number requested
if (appConfigs.length != appManifest.apps.length) {
F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest);
return;
}
// Fn for loading manifest Styles
var _loadStyles = function(styles, cb) {
// Attempt to use the user provided method
if (_config.loadStyles) {
_config.loadStyles(styles, cb);
}
else {
// load styles, see #101
var stylesFragment = null,
useCreateStyleSheet = !! document.createStyleSheet;
jQuery.each(styles, function(i, e) {
if (useCreateStyleSheet) {
document.createStyleSheet(e);
}
else {
stylesFragment = stylesFragment || [];
stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>');
}
});
if (stylesFragment) {
jQuery('head').append(stylesFragment.join(''));
}
cb();
}
};
// Fn for loading manifest Scripts
var _loadScripts = function(scripts, cb) {
// Attempt to use the user provided method
if (_config.loadScripts) {
_config.loadScripts(scripts, cb);
}
else {
if (scripts.length) {
var scriptCount = scripts.length;
var scriptsLoaded = 0;
// Check for IE10+ so that we don't rely on onreadystatechange
var readyStates = ('addEventListener' in window) ? {} : {
'loaded': true,
'complete': true
};
// Log and emit event for the failed (400,500) scripts
var _error = function(e) {
setTimeout(function() {
var evtData = {
src: e.target.src,
appId: appConfigs[0].appId
};
// Send error to console
F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\'');
// Emit event
F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData);
if (!_bUsesAppHandlers) {
_appScriptLoadFailed(appConfigs[0], evtData.src);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
appConfigs[0],
evtData.src
);
}
}, _config.scriptErrorTimeout); // Defaults to 7000
};
// Load scripts and eval inlines once complete
jQuery.each(scripts, function(i, e) {
var doc = document,
script = doc.createElement('script'),
resourceUrl = e;
// If in debugMode, add cache buster to each script URL
if (_config.debugMode) {
resourceUrl += '?cachebuster=' + new Date().getTime();
}
// Scripts needed to be loaded in order they're defined in the AppManifest
script.async = false;
// Add other attrs
script.src = resourceUrl;
script.type = 'text/javascript';
script.charset = 'utf-8';
script.onerror = _error;
// Use a closure for the load event so that we can dereference the original script
script.onload = script.onreadystatechange = function(e) {
e = e || window.event; // For older IE
if (e.type == 'load' || readyStates[script.readyState]) {
// Done, cleanup
script.onload = script.onreadystatechange = script.onerror = null;
// Dereference script
script = null;
// Are we done loading all scripts for this app?
if (++scriptsLoaded === scriptCount) {
cb();
}
}
};
doc.body.appendChild(script);
});
}
else {
cb();
}
}
};
var _loadInlineScripts = function(inlines, cb) {
// Attempt to use the user provided method
if (_config.loadInlineScripts) {
_config.loadInlineScripts(inlines, cb);
}
else {
for (var i = 0, len = inlines.length; i < len; i++) {
try {
eval(inlines[i]);
}
catch (exception) {
F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]);
if (!_bUsesAppHandlers) {
_appScriptLoadFailed(appConfigs[0], exception);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
appConfigs[0],
exception
);
}
}
}
cb();
}
};
// Determine whether an element has been added to the page
var elementInDocument = function(element) {
if (element) {
while (element.parentNode) {
element = element.parentNode;
if (element === document) {
return true;
}
}
}
return false;
};
// Fn for loading manifest app html
var _loadHtml = function(apps) {
jQuery.each(apps, function(i, a) {
if (!_bUsesAppHandlers) {
// load html and save the root node
appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html));
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfigs[i], // the app config
_outerHtml(a.html)
);
var appId = appConfigs[i].appId;
var root = appConfigs[i].root;
if (!root) {
throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.');
}
if (!elementInDocument(root)) {
throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfigs[i] // the app config
);
if (!F2.isNativeDOMNode(root)) {
throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.');
}
$(root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId);
}
// init events
_initAppEvents(appConfigs[i]);
});
};
// Pull out the manifest data
var scripts = appManifest.scripts || [];
var styles = appManifest.styles || [];
var inlines = appManifest.inlineScripts || [];
var apps = appManifest.apps || [];
// Finally, load the styles, html, and scripts
_loadStyles(styles, function() {
// Put the html on the page
_loadHtml(apps);
// Add the script content to the page
_loadScripts(scripts, function() {
// Load any inline scripts
_loadInlineScripts(inlines, function() {
// Create the apps
jQuery.each(appConfigs, function(i, a) {
_createAppInstance(a, appManifest.apps[i]);
});
});
});
});
};
/**
* Loads the app's html/css/javascript into an iframe
* @method loadSecureApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the
* page.
*/
var _loadSecureApp = function(appConfig, appManifest) {
// make sure the container is configured for secure apps
if (_config.secureAppPagePath) {
if (!_bUsesAppHandlers) {
// create the html container for the iframe
appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>'));
}
else {
var $root = jQuery(appConfig.root);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfig, // the app config
appManifest.html
);
if ($root.parents('body:first').length === 0) {
throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfig // the app config
);
if (!appConfig.root) {
throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
if (!F2.isNativeDOMNode(appConfig.root)) {
throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId);
}
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// init events
_initAppEvents(appConfig);
// create RPC socket
F2.Rpc.register(appConfig, appManifest);
}
else {
F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.');
}
};
var _outerHtml = function(html) {
return jQuery('<div></div>').append(html).html();
};
/**
* Checks if the app is valid
* @method _validateApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @returns {bool} True if the app is valid
*/
var _validateApp = function(appConfig) {
// check for valid app configurations
if (!appConfig.appId) {
F2.log('"appId" missing from app object');
return false;
}
else if (!appConfig.root && !appConfig.manifestUrl) {
F2.log('"manifestUrl" missing from app object');
return false;
}
return true;
};
/**
* Checks if the ContainerConfig is valid
* @method _validateContainerConfig
* @private
* @returns {bool} True if the config is valid
*/
var _validateContainerConfig = function() {
if (_config) {
if (_config.xhr) {
if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) {
throw ('ContainerConfig.xhr should be a function or an object');
}
if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') {
throw ('ContainerConfig.xhr.dataType should be a function');
}
if (_config.xhr.type && typeof _config.xhr.type !== 'function') {
throw ('ContainerConfig.xhr.type should be a function');
}
if (_config.xhr.url && typeof _config.xhr.url !== 'function') {
throw ('ContainerConfig.xhr.url should be a function');
}
}
}
return true;
};
return {
/**
* Gets the current list of apps in the container
* @method getContainerState
* @returns {Array} An array of objects containing the appId
*/
getContainerState: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.getContainerState()');
return;
}
return jQuery.map(_apps, function(app) {
return {
appId: app.config.appId
};
});
},
/**
* Initializes the container. This method must be called before performing
* any other actions in the container.
* @method init
* @param {F2.ContainerConfig} config The configuration object
*/
init: function(config) {
_config = config || {};
_validateContainerConfig();
_hydrateContainerConfig(_config);
// dictates whether we use the old logic or the new logic.
// TODO: Remove in v2.0
_bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed);
// only establish RPC connection if the container supports the secure app page
if ( !! _config.secureAppPagePath || _config.isSecureAppPage) {
F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false);
}
F2.UI.init(_config);
if (!_config.isSecureAppPage) {
_initContainerEvents();
}
},
/**
* Has the container been init?
* @method isInit
* @return {bool} True if the container has been init
*/
isInit: _isInit,
/**
* Begins the loading process for all apps and/or initialization process for pre-loaded apps.
* The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will
* contain the app's unique instanceId within the container. If the
* {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered
* to be a pre-loaded app and will be handled accordingly. Optionally, the
* {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those
* assets will be used instead of making a request.
* @method registerApps
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {Array} [appManifests] An array of
* {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* objects. This array must be the same length as the apps array that is
* objects. This array must be the same length as the apps array that is
* passed in. This can be useful if apps are loaded on the server-side and
* passed down to the client.
* @example
* Traditional App requests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app2',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Pre-loaded and tradition apps mixed.
*
* // Pre-loaded apps and traditional f2 app configs
* // you can preload the same app multiple times as long as you have a unique root for each
* var arConfigs = [
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-1',
* manifestUrl: ''
* },
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-2',
* manifestUrl: ''
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Apps with predefined manifests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app2', context: {}}
* ];
*
* // Pre requested manifest responses
* var arManifests = [
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App 2!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/App2Class.js'],
* styles: ['http://www.domain.com/css/App2Styles.css']
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs, arManifests);
*/
registerApps: function(appConfigs, appManifests) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.registerApps()');
return;
}
else if (!appConfigs) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
}
var appStack = [];
var batches = {};
var callbackStack = {};
var haveManifests = false;
appConfigs = [].concat(appConfigs);
appManifests = [].concat(appManifests || []);
haveManifests = !! appManifests.length;
// appConfigs must have a length
if (!appConfigs.length) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
// ensure that the array of apps and manifests are qual
}
else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) {
F2.log('The length of "apps" does not equal the length of "appManifests"');
return;
}
// validate each app and assign it an instanceId
// then determine which apps can be batched together
jQuery.each(appConfigs, function(i, a) {
// add properties and methods
a = _createAppConfig(a);
// Will set to itself, for preloaded apps, or set to null for apps that aren't already
// on the page.
a.root = a.root || null;
// we validate the app after setting the root property because pre-load apps do no require
// manifest url
if (!_validateApp(a)) {
return; // move to the next app
}
// save app
_apps[a.instanceId] = {
config: a
};
// If the root property is defined then this app is considered to be preloaded and we will
// run it through that logic.
if (a.root) {
if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) {
F2.log('AppConfig invalid for pre-load, not a valid string and not dom node');
F2.log('AppConfig instance:', a);
throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.');
}
else if (jQuery(a.root).length != 1) {
F2.log('AppConfig invalid for pre-load, root not unique');
F2.log('AppConfig instance:', a);
F2.log('Number of dom node instances:', jQuery(a.root).length);
throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.');
}
// instantiate F2.App
_createAppInstance(a);
// init events
_initAppEvents(a);
// Continue on in the .each loop, no need to continue because the app is on the page
// the js in initialized, and it is ready to role.
return; // equivalent to continue in .each
}
if (!_bUsesAppHandlers) {
// fire beforeAppRender
a.root = _beforeAppRender(a);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_CREATE_ROOT,
a // the app config
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_BEFORE,
a // the app config
);
}
// if we have the manifest, go ahead and load the app
if (haveManifests) {
_loadApps(a, appManifests[i]);
}
else {
// check if this app can be batched
if (a.enableBatchRequests && !a.isSecure) {
batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || [];
batches[a.manifestUrl.toLowerCase()].push(a);
}
else {
appStack.push({
apps: [a],
url: a.manifestUrl
});
}
}
});
// we don't have the manifests, go ahead and load them
if (!haveManifests) {
// add the batches to the appStack
jQuery.each(batches, function(i, b) {
appStack.push({
url: i,
apps: b
});
});
// if an app is being loaded more than once on the page, there is the
// potential that the jsonp callback will be clobbered if the request
// for the AppManifest for the app comes back at the same time as
// another request for the same app. We'll create a callbackStack
// that will ensure that requests for the same app are loaded in order
// rather than at the same time
jQuery.each(appStack, function(i, req) {
// define the callback function based on the first app's App ID
var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId;
// push the request onto the callback stack
callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || [];
callbackStack[jsonpCallback].push(req);
});
// loop through each item in the callback stack and make the request
// for the AppManifest. When the request is complete, pop the next
// request off the stack and make the request.
jQuery.each(callbackStack, function(i, requests) {
var manifestRequest = function(jsonpCallback, req) {
if (!req) {
return;
}
// setup defaults and callbacks
var url = req.url,
type = 'GET',
dataType = 'jsonp',
completeFunc = function() {
manifestRequest(i, requests.pop());
},
errorFunc = function() {
jQuery.each(req.apps, function(idx, item) {
F2.log('Removed failed ' + item.name + ' app', item);
F2.removeApp(item.instanceId);
});
},
successFunc = function(appManifest) {
_loadApps(req.apps, appManifest);
};
// optionally fire xhr overrides
if (_config.xhr && _config.xhr.dataType) {
dataType = _config.xhr.dataType(req.url, req.apps);
if (typeof dataType !== 'string') {
throw ('ContainerConfig.xhr.dataType should return a string');
}
}
if (_config.xhr && _config.xhr.type) {
type = _config.xhr.type(req.url, req.apps);
if (typeof type !== 'string') {
throw ('ContainerConfig.xhr.type should return a string');
}
}
if (_config.xhr && _config.xhr.url) {
url = _config.xhr.url(req.url, req.apps);
if (typeof url !== 'string') {
throw ('ContainerConfig.xhr.url should return a string');
}
}
// setup the default request function if an override is not present
var requestFunc = _config.xhr;
if (typeof requestFunc !== 'function') {
requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) {
jQuery.ajax({
url: url,
type: type,
data: {
params: F2.stringify(req.apps, F2.appConfigReplacer)
},
jsonp: false, // do not put 'callback=' in the query string
jsonpCallback: jsonpCallback, // Unique function name
dataType: dataType,
success: successCallback,
error: function(jqxhr, settings, exception) {
F2.log('Failed to load app(s)', exception.toString(), req.apps);
errorCallback();
},
complete: completeCallback
});
};
}
requestFunc(url, req.apps, successFunc, errorFunc, completeFunc);
};
manifestRequest(i, requests.pop());
});
}
},
/**
* Removes all apps from the container
* @method removeAllApps
*/
removeAllApps: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeAllApps()');
return;
}
jQuery.each(_apps, function(i, a) {
F2.removeApp(a.config.instanceId);
});
},
/**
* Removes an app from the container
* @method removeApp
* @param {string} instanceId The app's instanceId
*/
removeApp: function(instanceId) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeApp()');
return;
}
if (_apps[instanceId]) {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_AFTER,
_apps[instanceId] // the app instance
);
delete _apps[instanceId];
}
}
};
})());
exports.F2 = F2;
if (typeof define !== 'undefined' && define.amd) {
define(function() {
return F2;
});
}
})(typeof exports !== 'undefined' ? exports : window); |
fields/types/money/MoneyField.js | stunjiturner/keystone | import Field from '../Field';
import React from 'react';
import { FormInput } from 'elemental';
module.exports = Field.create({
displayName: 'MoneyField',
valueChanged (event) {
var newValue = event.target.value.replace(/[^\d\s\,\.\$€£¥]/g, '');
if (newValue === this.props.value) return;
this.props.onChange({
path: this.props.path,
value: newValue
});
},
renderField () {
return <FormInput name={this.props.path} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" />;
}
});
|
Libraries/react-native/react-native-interface.js | Suninus/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
// see also react-native.js
declare var __DEV__: boolean;
declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: any; /*?{
inject: ?((stuff: Object) => void)
};*/
declare var fetch: any;
declare var Headers: any;
declare var Request: any;
declare var Response: any;
declare module requestAnimationFrame {
declare var exports: (callback: any) => any;
}
|
ajax/libs/react/15.1.0/react-with-addons.min.js | humbletim/cdnjs | /**
* React (with addons) v15.1.0
*
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.React=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t,n){"use strict";var r=e(44),o=e(162),i={focusDOMComponent:function(){o(r.getNodeFromInstance(this))}};t.exports=i},{162:162,44:44}],2:[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 S.topCompositionStart:return M.compositionStart;case S.topCompositionEnd:return M.compositionEnd;case S.topCompositionUpdate:return M.compositionUpdate}}function a(e,t){return e===S.topKeyDown&&t.keyCode===_}function s(e,t){switch(e){case S.topKeyUp:return-1!==b.indexOf(t.keyCode);case S.topKeyDown:return t.keyCode!==_;case S.topKeyPress:case S.topMouseDown:case S.topBlur:return!0;default:return!1}}function u(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(E?o=i(e):R?s(e,n)&&(o=M.compositionEnd):a(e,n)&&(o=M.compositionStart),!o)return null;N&&(R||o!==M.compositionStart?o===M.compositionEnd&&R&&(l=R.getData()):R=m.getPooled(r));var c=g.getPooled(o,t,n,r);if(l)c.data=l;else{var p=u(n);null!==p&&(c.data=p)}return h.accumulateTwoPhaseDispatches(c),c}function c(e,t){switch(e){case S.topCompositionEnd:return u(t);case S.topKeyPress:var n=t.which;return n!==P?null:(k=!0,w);case S.topTextInput:var r=t.data;return r===w&&k?null:r;default:return null}}function p(e,t){if(R){if(e===S.topCompositionEnd||s(e,t)){var n=R.getData();return m.release(R),R=null,n}return null}switch(e){case S.topPaste:return null;case S.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case S.topCompositionEnd:return N?null:t.data;default:return null}}function d(e,t,n,r){var o;if(o=x?c(e,n):p(e,n),!o)return null;var i=y.getPooled(M.beforeInput,t,n,r);return i.data=o,h.accumulateTwoPhaseDispatches(i),i}var f=e(16),h=e(20),v=e(154),m=e(21),g=e(108),y=e(112),C=e(172),b=[9,13,27,32],_=229,E=v.canUseDOM&&"CompositionEvent"in window,T=null;v.canUseDOM&&"documentMode"in document&&(T=document.documentMode);var x=v.canUseDOM&&"TextEvent"in window&&!T&&!r(),N=v.canUseDOM&&(!E||T&&T>8&&11>=T),P=32,w=String.fromCharCode(P),S=f.topLevelTypes,M={beforeInput:{phasedRegistrationNames:{bubbled:C({onBeforeInput:null}),captured:C({onBeforeInputCapture:null})},dependencies:[S.topCompositionEnd,S.topKeyPress,S.topTextInput,S.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:C({onCompositionEnd:null}),captured:C({onCompositionEndCapture:null})},dependencies:[S.topBlur,S.topCompositionEnd,S.topKeyDown,S.topKeyPress,S.topKeyUp,S.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:C({onCompositionStart:null}),captured:C({onCompositionStartCapture:null})},dependencies:[S.topBlur,S.topCompositionStart,S.topKeyDown,S.topKeyPress,S.topKeyUp,S.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:C({onCompositionUpdate:null}),captured:C({onCompositionUpdateCapture:null})},dependencies:[S.topBlur,S.topCompositionUpdate,S.topKeyDown,S.topKeyPress,S.topKeyUp,S.topMouseDown]}},k=!1,R=null,D={eventTypes:M,extractEvents:function(e,t,n,r){return[l(e,t,n,r),d(e,t,n,r)]}};t.exports=D},{108:108,112:112,154:154,16:16,172:172,20:20,21:21}],3:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!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:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},s={isUnitlessNumber:o,shorthandPropertyExpansions:a};t.exports=s},{}],4:[function(e,t,n){"use strict";var r=e(3),o=e(154),i=(e(75),e(156),e(125)),a=e(167),s=e(174),u=(e(178),s(function(e){return a(e)})),l=!1,c="cssFloat";if(o.canUseDOM){var p=document.createElement("div").style;try{p.font=""}catch(d){l=!0}void 0===document.documentElement.style.cssFloat&&(c="styleFloat")}var f={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=u(r)+":",n+=i(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var o=e.style;for(var a in t)if(t.hasOwnProperty(a)){var s=i(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=c),s)o[a]=s;else{var u=l&&r.shorthandPropertyExpansions[a];if(u)for(var p in u)o[p]="";else o[a]=""}}}};t.exports=f},{125:125,154:154,156:156,167:167,174:174,178:178,3:3,75:75}],5:[function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=e(179),i=e(26),a=e(168);o(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){e.length!==t.length?a(!1):void 0,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}},checkpoint:function(){return this._callbacks?this._callbacks.length:0},rollback:function(e){this._callbacks&&(this._callbacks.length=e,this._contexts.length=e)},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),i.addPoolingTo(r),t.exports=r},{168:168,179:179,26:26}],6:[function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=x.getPooled(k.change,D,e,N(e));b.accumulateTwoPhaseDispatches(t),T.batchedUpdates(i,t)}function i(e){C.enqueueEvents(e),C.processEventQueue(!1)}function a(e,t){R=e,D=t,R.attachEvent("onchange",o)}function s(){R&&(R.detachEvent("onchange",o),R=null,D=null)}function u(e,t){return e===M.topChange?t:void 0}function l(e,t,n){e===M.topFocus?(s(),a(t,n)):e===M.topBlur&&s()}function c(e,t){R=e,D=t,A=e.value,O=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(R,"value",U),R.attachEvent?R.attachEvent("onpropertychange",d):R.addEventListener("propertychange",d,!1)}function p(){R&&(delete R.value,R.detachEvent?R.detachEvent("onpropertychange",d):R.removeEventListener("propertychange",d,!1),R=null,D=null,A=null,O=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==A&&(A=t,o(e))}}function f(e,t){return e===M.topInput?t:void 0}function h(e,t,n){e===M.topFocus?(p(),c(t,n)):e===M.topBlur&&p()}function v(e,t){return e!==M.topSelectionChange&&e!==M.topKeyUp&&e!==M.topKeyDown||!R||R.value===A?void 0:(A=R.value,D)}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function g(e,t){return e===M.topClick?t:void 0}var y=e(16),C=e(17),b=e(20),_=e(154),E=e(44),T=e(99),x=e(110),N=e(133),P=e(140),w=e(141),S=e(172),M=y.topLevelTypes,k={change:{phasedRegistrationNames:{bubbled:S({onChange:null}),captured:S({onChangeCapture:null})},dependencies:[M.topBlur,M.topChange,M.topClick,M.topFocus,M.topInput,M.topKeyDown,M.topKeyUp,M.topSelectionChange]}},R=null,D=null,A=null,O=null,I=!1;_.canUseDOM&&(I=P("change")&&(!("documentMode"in document)||document.documentMode>8));var L=!1;_.canUseDOM&&(L=P("input")&&(!("documentMode"in document)||document.documentMode>11));var U={get:function(){return O.get.call(this)},set:function(e){A=""+e,O.set.call(this,e)}},F={eventTypes:k,extractEvents:function(e,t,n,o){var i,a,s=t?E.getNodeFromInstance(t):window;if(r(s)?I?i=u:a=l:w(s)?L?i=f:(i=v,a=h):m(s)&&(i=g),i){var c=i(e,t);if(c){var p=x.getPooled(k.change,c,n,o);return p.type="change",b.accumulateTwoPhaseDispatches(p),p}}a&&a(e,s,t)}};t.exports=F},{110:110,133:133,140:140,141:141,154:154,16:16,17:17,172:172,20:20,44:44,99:99}],7:[function(e,t,n){"use strict";function r(e,t){return Array.isArray(t)&&(t=t[1]),t?t.nextSibling:e.firstChild}function o(e,t,n){c.insertTreeBefore(e,t,n)}function i(e,t,n){Array.isArray(t)?s(e,t[0],t[1],n):m(e,t,n)}function a(e,t){if(Array.isArray(t)){var n=t[1];t=t[0],u(e,t,n),e.removeChild(n)}e.removeChild(t)}function s(e,t,n,r){for(var o=t;;){var i=o.nextSibling;if(m(e,o,r),o===n)break;o=i}}function u(e,t,n){for(;;){var r=t.nextSibling;if(r===n)break;e.removeChild(r)}}function l(e,t,n){var r=e.parentNode,o=e.nextSibling;o===t?n&&m(r,document.createTextNode(n),o):n?(v(o,n),u(r,o,t)):u(r,e,t)}var c=e(8),p=e(12),d=e(80),f=(e(44),e(75),e(124)),h=e(145),v=e(146),m=f(function(e,t,n){e.insertBefore(t,n)}),g=p.dangerouslyReplaceNodeWithMarkup,y={dangerouslyReplaceNodeWithMarkup:g,replaceDelimitedText:l,processUpdates:function(e,t){for(var n=0;n<t.length;n++){var s=t[n];switch(s.type){case d.INSERT_MARKUP:o(e,s.content,r(e,s.afterNode));break;case d.MOVE_EXISTING:i(e,s.fromNode,r(e,s.afterNode));break;case d.SET_MARKUP:h(e,s.content);break;case d.TEXT_CONTENT:v(e,s.content);break;case d.REMOVE_NODE:a(e,s.fromNode)}}}};t.exports=y},{12:12,124:124,145:145,146:146,44:44,75:75,8:8,80:80}],8:[function(e,t,n){"use strict";function r(e){if(v){var t=e.node,n=e.children;if(n.length)for(var r=0;r<n.length;r++)m(t,n[r],null);else null!=e.html?t.innerHTML=e.html:null!=e.text&&d(t,e.text)}}function o(e,t){e.parentNode.replaceChild(t.node,e),r(t)}function i(e,t){v?e.children.push(t):e.node.appendChild(t.node)}function a(e,t){v?e.html=t:e.node.innerHTML=t}function s(e,t){v?e.text=t:d(e.node,t)}function u(){return this.node.nodeName}function l(e){return{node:e,children:[],html:null,text:null,toString:u}}var c=e(9),p=e(124),d=e(146),f=1,h=11,v="undefined"!=typeof document&&"number"==typeof document.documentMode||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&/\bEdge\/\d/.test(navigator.userAgent),m=p(function(e,t,n){t.node.nodeType===h||t.node.nodeType===f&&"object"===t.node.nodeName.toLowerCase()&&(null==t.node.namespaceURI||t.node.namespaceURI===c.html)?(r(t),e.insertBefore(t.node,n)):(e.insertBefore(t.node,n),r(t))});l.insertTreeBefore=m,l.replaceChildWithTree=o,l.queueChild=i,l.queueHTML=a,l.queueText=s,t.exports=l},{124:124,146:146,9:9}],9:[function(e,t,n){"use strict";var r={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};t.exports=r},{}],10:[function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=e(168),i={MUST_USE_PROPERTY:1,HAS_SIDE_EFFECTS:2,HAS_BOOLEAN_VALUE:4,HAS_NUMERIC_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:24,HAS_OVERLOADED_BOOLEAN_VALUE:32,injectDOMPropertyConfig:function(e){var t=i,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},u=e.DOMAttributeNames||{},l=e.DOMPropertyNames||{},c=e.DOMMutationMethods||{};e.isCustomAttribute&&s._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var p in n){s.properties.hasOwnProperty(p)?o(!1):void 0;var d=p.toLowerCase(),f=n[p],h={attributeName:d,attributeNamespace:null,propertyName:p,mutationMethod:null,mustUseProperty:r(f,t.MUST_USE_PROPERTY),hasSideEffects:r(f,t.HAS_SIDE_EFFECTS),hasBooleanValue:r(f,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(f,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(f,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(f,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(!h.mustUseProperty&&h.hasSideEffects?o(!1):void 0,h.hasBooleanValue+h.hasNumericValue+h.hasOverloadedBooleanValue<=1?void 0:o(!1),u.hasOwnProperty(p)){var v=u[p];h.attributeName=v}a.hasOwnProperty(p)&&(h.attributeNamespace=a[p]),l.hasOwnProperty(p)&&(h.propertyName=l[p]),c.hasOwnProperty(p)&&(h.mutationMethod=c[p]),s.properties[p]=h}}},a=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",s={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:a,ATTRIBUTE_NAME_CHAR:a+"\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<s._isCustomAttributeFunctions.length;t++){var n=s._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},injection:i};t.exports=s},{168:168}],11:[function(e,t,n){"use strict";function r(e){return l.hasOwnProperty(e)?!0:u.hasOwnProperty(e)?!1:s.test(e)?(l[e]=!0,!0):(u[e]=!0,!1)}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&1>t||e.hasOverloadedBooleanValue&&t===!1}var i=e(10),a=(e(44),e(52),e(75),e(143)),s=(e(178),new RegExp("^["+i.ATTRIBUTE_NAME_START_CHAR+"]["+i.ATTRIBUTE_NAME_CHAR+"]*$")),u={},l={},c={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+a(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return i.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(e){e.setAttribute(i.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(e,t){var n=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&t===!0?r+'=""':r+"="+a(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+a(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+a(t):""},setValueForProperty:function(e,t,n){var r=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else{if(o(r,n))return void this.deleteValueForProperty(e,t);if(r.mustUseProperty){var s=r.propertyName;r.hasSideEffects&&""+e[s]==""+n||(e[s]=n)}else{var u=r.attributeName,l=r.attributeNamespace;l?e.setAttributeNS(l,u,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?e.setAttribute(u,""):e.setAttribute(u,""+n)}}}else if(i.isCustomAttribute(t))return void c.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){r(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){var n=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseProperty){var o=n.propertyName;n.hasBooleanValue?e[o]=!1:n.hasSideEffects&&""+e[o]==""||(e[o]="")}else e.removeAttribute(n.attributeName)}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=c},{10:10,143:143,178:178,44:44,52:52,75:75}],12:[function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=e(8),i=e(154),a=e(159),s=e(160),u=e(164),l=e(168),c=/^(<[^ \/>]+)/,p="data-danger-index",d={dangerouslyRenderMarkup:function(e){i.canUseDOM?void 0:l(!1);for(var t,n={},o=0;o<e.length;o++)e[o]?void 0:l(!1),t=r(e[o]),t=u(t)?t:"*",n[t]=n[t]||[],n[t][o]=e[o];var d=[],f=0;for(t in n)if(n.hasOwnProperty(t)){var h,v=n[t];for(h in v)if(v.hasOwnProperty(h)){var m=v[h];v[h]=m.replace(c,"$1 "+p+'="'+h+'" ')}for(var g=a(v.join(""),s),y=0;y<g.length;++y){var C=g[y];C.hasAttribute&&C.hasAttribute(p)&&(h=+C.getAttribute(p),C.removeAttribute(p),d.hasOwnProperty(h)?l(!1):void 0,d[h]=C,f+=1)}}return f!==d.length?l(!1):void 0,d.length!==e.length?l(!1):void 0,d},dangerouslyReplaceNodeWithMarkup:function(e,t){if(i.canUseDOM?void 0:l(!1),t?void 0:l(!1),"HTML"===e.nodeName?l(!1):void 0,"string"==typeof t){var n=a(t,s)[0];e.parentNode.replaceChild(n,e)}else o.replaceChildWithTree(e,t)}};t.exports=d},{154:154,159:159,160:160,164:164,168:168,8:8}],13:[function(e,t,n){"use strict";var r=e(172),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null})];t.exports=o},{172:172}],14:[function(e,t,n){"use strict";var r={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},o={getNativeProps:function(e,t){if(!t.disabled)return t;var n={};for(var o in t)!r[o]&&t.hasOwnProperty(o)&&(n[o]=t[o]);return n}};t.exports=o},{}],15:[function(e,t,n){"use strict";var r=e(16),o=e(20),i=e(44),a=e(114),s=e(172),u=r.topLevelTypes,l={mouseEnter:{registrationName:s({onMouseEnter:null}),dependencies:[u.topMouseOut,u.topMouseOver]},mouseLeave:{registrationName:s({onMouseLeave:null}),dependencies:[u.topMouseOut,u.topMouseOver]}},c={eventTypes:l,extractEvents:function(e,t,n,r){if(e===u.topMouseOver&&(n.relatedTarget||n.fromElement))return null;if(e!==u.topMouseOut&&e!==u.topMouseOver)return null;var s;if(r.window===r)s=r;else{var c=r.ownerDocument;s=c?c.defaultView||c.parentWindow:window}var p,d;if(e===u.topMouseOut){p=t;var f=n.relatedTarget||n.toElement;d=f?i.getClosestInstanceFromNode(f):null}else p=null,d=t;if(p===d)return null;var h=null==p?s:i.getNodeFromInstance(p),v=null==d?s:i.getNodeFromInstance(d),m=a.getPooled(l.mouseLeave,p,n,r);m.type="mouseleave",m.target=h,m.relatedTarget=v;var g=a.getPooled(l.mouseEnter,d,n,r);return g.type="mouseenter",g.target=v,g.relatedTarget=h,o.accumulateEnterLeaveDispatches(m,g,p,d),[m,g]}};t.exports=c},{114:114,16:16,172:172,20:20,44:44}],16:[function(e,t,n){"use strict";var r=e(171),o=r({bubbled:null,captured:null}),i=r({topAbort:null,topAnimationEnd:null,topAnimationIteration:null,topAnimationStart:null,topBlur:null,topCanPlay:null,topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topInvalid:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topTransitionEnd:null,topVolumeChange:null,topWaiting:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:o};t.exports=a},{171:171}],17:[function(e,t,n){"use strict";var r=e(18),o=e(19),i=e(67),a=e(121),s=e(129),u=e(168),l={},c=null,p=function(e,t){e&&(o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},d=function(e){return p(e,!0)},f=function(e){return p(e,!1)},h={injection:{injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},putListener:function(e,t,n){"function"!=typeof n?u(!1):void 0;var o=l[t]||(l[t]={});o[e._rootNodeID]=n;var i=r.registrationNameModules[t];i&&i.didPutListener&&i.didPutListener(e,t,n)},getListener:function(e,t){var n=l[t];return n&&n[e._rootNodeID]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=l[t];o&&delete o[e._rootNodeID]},deleteAllListeners:function(e){for(var t in l)if(l[t][e._rootNodeID]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete l[t][e._rootNodeID]}},extractEvents:function(e,t,n,o){for(var i,s=r.plugins,u=0;u<s.length;u++){var l=s[u];if(l){var c=l.extractEvents(e,t,n,o);c&&(i=a(i,c))}}return i},enqueueEvents:function(e){e&&(c=a(c,e))},processEventQueue:function(e){var t=c;c=null,e?s(t,d):s(t,f),c?u(!1):void 0,i.rethrowCaughtError()},__purge:function(){l={}},__getListenerBank:function(){return l}};t.exports=h},{121:121,129:129,168:168,18:18,19:19,67:67}],18:[function(e,t,n){"use strict";function r(){if(s)for(var e in u){var t=u[e],n=s.indexOf(e);if(n>-1?void 0:a(!1),!l.plugins[n]){t.extractEvents?void 0:a(!1),l.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)?void 0:a(!1)}}}function o(e,t,n){l.eventNameDispatchConfigs.hasOwnProperty(n)?a(!1):void 0,l.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var s=r[o];i(s,t,n)}return!0}return e.registrationName?(i(e.registrationName,t,n),!0):!1}function i(e,t,n){l.registrationNameModules[e]?a(!1):void 0,l.registrationNameModules[e]=t,l.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=e(168),s=null,u={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){s?a(!1):void 0,s=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];u.hasOwnProperty(n)&&u[n]===o||(u[n]?a(!1):void 0,u[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(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[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},{168:168}],19:[function(e,t,n){"use strict";function r(e){return e===y.topMouseUp||e===y.topTouchEnd||e===y.topTouchCancel}function o(e){return e===y.topMouseMove||e===y.topTouchMove}function i(e){return e===y.topMouseDown||e===y.topTouchStart}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=C.getNodeFromInstance(r),t?v.invokeGuardedCallbackWithCatch(o,n,e):v.invokeGuardedCallback(o,n,e),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)a(e,t,n[o],r[o]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchInstances=null}function u(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function l(e){var t=u(e);return e._dispatchInstances=null,e._dispatchListeners=null,t}function c(e){var t=e._dispatchListeners,n=e._dispatchInstances;Array.isArray(t)?m(!1):void 0,e.currentTarget=t?C.getNodeFromInstance(n):null;var r=t?t(e):null;return e.currentTarget=null,e._dispatchListeners=null,e._dispatchInstances=null,r}function p(e){return!!e._dispatchListeners}var d,f,h=e(16),v=e(67),m=e(168),g=(e(178),{injectComponentTree:function(e){d=e},injectTreeTraversal:function(e){f=e}}),y=h.topLevelTypes,C={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:c,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:l,hasDispatches:p,getInstanceFromNode:function(e){return d.getInstanceFromNode(e)},getNodeFromInstance:function(e){return d.getNodeFromInstance(e)},isAncestor:function(e,t){return f.isAncestor(e,t)},getLowestCommonAncestor:function(e,t){return f.getLowestCommonAncestor(e,t)},getParentInstance:function(e){return f.getParentInstance(e)},traverseTwoPhase:function(e,t,n){return f.traverseTwoPhase(e,t,n)},traverseEnterLeave:function(e,t,n,r,o){return f.traverseEnterLeave(e,t,n,r,o)},injection:g};t.exports=C},{16:16,168:168,178:178,67:67}],20:[function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return C(e,r)}function o(e,t,n){var o=t?y.bubbled:y.captured,i=r(e,n,o);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchInstances=m(n._dispatchInstances,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&v.traverseTwoPhase(e._targetInst,o,e)}function a(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?v.getParentInstance(t):null;v.traverseTwoPhase(n,o,e)}}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=C(e,r);o&&(n._dispatchListeners=m(n._dispatchListeners,o),n._dispatchInstances=m(n._dispatchInstances,e))}}function u(e){e&&e.dispatchConfig.registrationName&&s(e._targetInst,null,e)}function l(e){g(e,i)}function c(e){g(e,a)}function p(e,t,n,r){v.traverseEnterLeave(n,r,s,e,t)}function d(e){g(e,u)}var f=e(16),h=e(17),v=e(19),m=e(121),g=e(129),y=(e(178),f.PropagationPhases),C=h.getListener,b={accumulateTwoPhaseDispatches:l,accumulateTwoPhaseDispatchesSkipTarget:c,accumulateDirectDispatches:d,accumulateEnterLeaveDispatches:p};t.exports=b},{121:121,129:129,16:16,17:17,178:178,19:19}],21:[function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=e(179),i=e(26),a=e(137);o(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=o.slice(e,s),this._fallbackText}}),i.addPoolingTo(r),t.exports=r},{137:137,179:179,26:26}],22:[function(e,t,n){"use strict";var r=e(10),o=r.injection.MUST_USE_PROPERTY,i=r.injection.HAS_BOOLEAN_VALUE,a=r.injection.HAS_SIDE_EFFECTS,s=r.injection.HAS_NUMERIC_VALUE,u=r.injection.HAS_POSITIVE_NUMERIC_VALUE,l=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE,c={isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+r.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:i,allowTransparency:0,alt:0,async:i,autoComplete:0,autoPlay:i,capture:i,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:o|i,cite:0,classID:0,className:0,cols:u,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:i,coords:0,crossOrigin:0,data:0,dateTime:0,"default":i,defer:i,dir:0,disabled:i,download:l,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:i,formTarget:0,frameBorder:0,headers:0,height:0,hidden:i,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:i,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:o|i,muted:o|i,name:0,nonce:0,noValidate:i,open:i,optimum:0,pattern:0,placeholder:0,poster:0,preload:0,profile:0,radioGroup:0,readOnly:i,rel:0,required:i,reversed:i,role:0,rows:u,rowSpan:s,sandbox:0,scope:0,scoped:i,scrolling:0,seamless:i,selected:o|i,shape:0,size:u,sizes:0,span:u,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:s,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:o|a,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,"typeof":0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:i,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{}};t.exports=c},{10:10}],23:[function(e,t,n){"use strict";function r(e){var t=/[=:]/g,n={"=":"=0",":":"=2"},r=(""+e).replace(t,function(e){return n[e]});return"$"+r}function o(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"},r="."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1);return(""+r).replace(t,function(e){return n[e]})}var i={escape:r,unescape:o};t.exports=i},{}],24:[function(e,t,n){"use strict";var r=e(76),o=e(94),i={linkState:function(e){return new r(this.state[e],o.createStateKeySetter(this,e))}};t.exports=i},{76:76,94:94}],25:[function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?l(!1):void 0}function o(e){r(e),null!=e.value||null!=e.onChange?l(!1):void 0}function i(e){r(e),null!=e.checked||null!=e.onChange?l(!1):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=e(87),u=e(86),l=e(168),c=(e(178),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),p={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},d={},f={checkPropTypes:function(e,t,n){for(var r in p){if(p.hasOwnProperty(r))var o=p[r](t,r,e,u.prop);o instanceof Error&&!(o.message in d)&&(d[o.message]=!0,a(n))}},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},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};t.exports=f},{168:168,178:178,86:86,87:87}],26:[function(e,t,n){"use strict";var r=e(168),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)},s=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},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)},l=function(e){var t=this;e instanceof t?void 0:r(!1),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=10,p=o,d=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||p,n.poolSize||(n.poolSize=c),n.release=l,n},f={addPoolingTo:d,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:s,fiveArgumentPooler:u
};t.exports=f},{168:168}],27:[function(e,t,n){"use strict";var r=e(179),o=e(32),i=e(34),a=e(33),s=e(48),u=e(64),l=(e(65),e(87)),c=e(100),p=e(142),d=(e(178),u.createElement),f=u.createFactory,h=u.cloneElement,v=r,m={Children:{map:o.map,forEach:o.forEach,count:o.count,toArray:o.toArray,only:p},Component:i,createElement:d,cloneElement:h,isValidElement:u.isValidElement,PropTypes:l,createClass:a.createClass,createFactory:f,createMixin:function(e){return e},DOM:s,version:c,__spread:v};t.exports=m},{100:100,142:142,178:178,179:179,32:32,33:33,34:34,48:48,64:64,65:65,87:87}],28:[function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=h++,d[e[m]]={}),d[e[m]]}var o,i=e(179),a=e(16),s=e(18),u=e(68),l=e(120),c=e(138),p=e(140),d={},f=!1,h=0,v={topAbort:"abort",topAnimationEnd:c("animationend")||"animationend",topAnimationIteration:c("animationiteration")||"animationiteration",topAnimationStart:c("animationstart")||"animationstart",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topTransitionEnd:c("transitionend")||"transitionend",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),g=i({},u,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(g.handleTopLevel),g.ReactEventListener=e}},setEnabled:function(e){g.ReactEventListener&&g.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!g.ReactEventListener||!g.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,o=r(n),i=s.registrationNameDependencies[e],u=a.topLevelTypes,l=0;l<i.length;l++){var c=i[l];o.hasOwnProperty(c)&&o[c]||(c===u.topWheel?p("wheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"wheel",n):p("mousewheel")?g.ReactEventListener.trapBubbledEvent(u.topWheel,"mousewheel",n):g.ReactEventListener.trapBubbledEvent(u.topWheel,"DOMMouseScroll",n):c===u.topScroll?p("scroll",!0)?g.ReactEventListener.trapCapturedEvent(u.topScroll,"scroll",n):g.ReactEventListener.trapBubbledEvent(u.topScroll,"scroll",g.ReactEventListener.WINDOW_HANDLE):c===u.topFocus||c===u.topBlur?(p("focus",!0)?(g.ReactEventListener.trapCapturedEvent(u.topFocus,"focus",n),g.ReactEventListener.trapCapturedEvent(u.topBlur,"blur",n)):p("focusin")&&(g.ReactEventListener.trapBubbledEvent(u.topFocus,"focusin",n),g.ReactEventListener.trapBubbledEvent(u.topBlur,"focusout",n)),o[u.topBlur]=!0,o[u.topFocus]=!0):v.hasOwnProperty(c)&&g.ReactEventListener.trapBubbledEvent(c,v[c],n),o[c]=!0)}},trapBubbledEvent:function(e,t,n){return g.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return g.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(void 0===o&&(o=document.createEvent&&"pageX"in document.createEvent("MouseEvent")),!o&&!f){var e=l.refreshScrollValues;g.ReactEventListener.monitorScrollValue(e),f=!0}}});t.exports=g},{120:120,138:138,140:140,16:16,179:179,18:18,68:68}],29:[function(e,t,n){"use strict";function r(e){var t="transition"+e+"Timeout",n="transition"+e;return function(e){if(e[n]){if(null==e[t])return new Error(t+" wasn't supplied to ReactCSSTransitionGroup: this can cause unreliable animations and won't be supported in a future version of React. See https://fb.me/react-animation-transition-group-timeout for more information.");if("number"!=typeof e[t])return new Error(t+" must be a number (in milliseconds)")}}}var o=e(179),i=e(27),a=e(97),s=e(30),u=i.createClass({displayName:"ReactCSSTransitionGroup",propTypes:{transitionName:s.propTypes.name,transitionAppear:i.PropTypes.bool,transitionEnter:i.PropTypes.bool,transitionLeave:i.PropTypes.bool,transitionAppearTimeout:r("Appear"),transitionEnterTimeout:r("Enter"),transitionLeaveTimeout:r("Leave")},getDefaultProps:function(){return{transitionAppear:!1,transitionEnter:!0,transitionLeave:!0}},_wrapChild:function(e){return i.createElement(s,{name:this.props.transitionName,appear:this.props.transitionAppear,enter:this.props.transitionEnter,leave:this.props.transitionLeave,appearTimeout:this.props.transitionAppearTimeout,enterTimeout:this.props.transitionEnterTimeout,leaveTimeout:this.props.transitionLeaveTimeout},e)},render:function(){return i.createElement(a,o({},this.props,{childFactory:this._wrapChild}))}});t.exports=u},{179:179,27:27,30:30,97:97}],30:[function(e,t,n){"use strict";var r=e(27),o=e(40),i=e(152),a=e(96),s=e(142),u=17,l=r.createClass({displayName:"ReactCSSTransitionGroupChild",propTypes:{name:r.PropTypes.oneOfType([r.PropTypes.string,r.PropTypes.shape({enter:r.PropTypes.string,leave:r.PropTypes.string,active:r.PropTypes.string}),r.PropTypes.shape({enter:r.PropTypes.string,enterActive:r.PropTypes.string,leave:r.PropTypes.string,leaveActive:r.PropTypes.string,appear:r.PropTypes.string,appearActive:r.PropTypes.string})]).isRequired,appear:r.PropTypes.bool,enter:r.PropTypes.bool,leave:r.PropTypes.bool,appearTimeout:r.PropTypes.number,enterTimeout:r.PropTypes.number,leaveTimeout:r.PropTypes.number},transition:function(e,t,n){var r=o.findDOMNode(this);if(!r)return void(t&&t());var s=this.props.name[e]||this.props.name+"-"+e,u=this.props.name[e+"Active"]||s+"-active",l=null,c=function(e){e&&e.target!==r||(clearTimeout(l),i.removeClass(r,s),i.removeClass(r,u),a.removeEndEventListener(r,c),t&&t())};i.addClass(r,s),this.queueClass(u),n?(l=setTimeout(c,n),this.transitionTimeouts.push(l)):a.addEndEventListener(r,c)},queueClass:function(e){this.classNameQueue.push(e),this.timeout||(this.timeout=setTimeout(this.flushClassNameQueue,u))},flushClassNameQueue:function(){this.isMounted()&&this.classNameQueue.forEach(i.addClass.bind(i,o.findDOMNode(this))),this.classNameQueue.length=0,this.timeout=null},componentWillMount:function(){this.classNameQueue=[],this.transitionTimeouts=[]},componentWillUnmount:function(){this.timeout&&clearTimeout(this.timeout),this.transitionTimeouts.forEach(function(e){clearTimeout(e)})},componentWillAppear:function(e){this.props.appear?this.transition("appear",e,this.props.appearTimeout):e()},componentWillEnter:function(e){this.props.enter?this.transition("enter",e,this.props.enterTimeout):e()},componentWillLeave:function(e){this.props.leave?this.transition("leave",e,this.props.leaveTimeout):e()},render:function(){return s(this.props.children)}});t.exports=l},{142:142,152:152,27:27,40:40,96:96}],31:[function(e,t,n){"use strict";function r(e,t,n){var r=void 0===e[n];null!=t&&r&&(e[n]=i(t))}var o=e(89),i=e(139),a=(e(23),e(148)),s=e(149),u=(e(178),{instantiateChildren:function(e,t,n){if(null==e)return null;var o={};return s(e,r,o),o},updateChildren:function(e,t,n,r,s){if(t||e){var u,l;for(u in t)if(t.hasOwnProperty(u)){l=e&&e[u];var c=l&&l._currentElement,p=t[u];if(null!=l&&a(c,p))o.receiveComponent(l,p,r,s),t[u]=l;else{l&&(n[u]=o.getNativeNode(l),o.unmountComponent(l,!1));var d=i(p);t[u]=d}}for(u in e)!e.hasOwnProperty(u)||t&&t.hasOwnProperty(u)||(l=e[u],n[u]=o.getNativeNode(l),o.unmountComponent(l,!1))}},unmountChildren:function(e,t){for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];o.unmountComponent(r,t)}}});t.exports=u},{139:139,148:148,149:149,178:178,23:23,89:89}],32:[function(e,t,n){"use strict";function r(e){return(""+e).replace(b,"$&/")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);g(e,i,r),o.release(r)}function s(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function u(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,s=e.context,u=a.call(s,t,e.count++);Array.isArray(u)?l(u,o,n,m.thatReturnsArgument):null!=u&&(v.isValidElement(u)&&(u=v.cloneAndReplaceKey(u,i+(!u.key||t&&t.key===u.key?"":r(u.key)+"/")+n)),o.push(u))}function l(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var l=s.getPooled(t,a,o,i);g(e,u,l),s.release(l)}function c(e,t,n){if(null==e)return e;var r=[];return l(e,r,null,t,n),r}function p(e,t,n){return null}function d(e,t){return g(e,p,null)}function f(e){var t=[];return l(e,t,null,m.thatReturnsArgument),t}var h=e(26),v=e(64),m=e(160),g=e(149),y=h.twoArgumentPooler,C=h.fourArgumentPooler,b=/\/+/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(o,y),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(s,C);var _={forEach:a,map:c,mapIntoWithKeyPrefixInternal:l,count:d,toArray:f};t.exports=_},{149:149,160:160,26:26,64:64}],33:[function(e,t,n){"use strict";function r(e,t){var n=E.hasOwnProperty(t)?E[t]:null;x.hasOwnProperty(t)&&(n!==b.OVERRIDE_BASE?m(!1):void 0),e&&(n!==b.DEFINE_MANY&&n!==b.DEFINE_MANY_MERGED?m(!1):void 0)}function o(e,t){if(t){"function"==typeof t?m(!1):void 0,f.isValidElement(t)?m(!1):void 0;var n=e.prototype,o=n.__reactAutoBindPairs;t.hasOwnProperty(C)&&T.mixins(e,t.mixins);for(var i in t)if(t.hasOwnProperty(i)&&i!==C){var a=t[i],l=n.hasOwnProperty(i);if(r(l,i),T.hasOwnProperty(i))T[i](e,a);else{var c=E.hasOwnProperty(i),p="function"==typeof a,d=p&&!c&&!l&&t.autobind!==!1;if(d)o.push(i,a),n[i]=a;else if(l){var h=E[i];!c||h!==b.DEFINE_MANY_MERGED&&h!==b.DEFINE_MANY?m(!1):void 0,h===b.DEFINE_MANY_MERGED?n[i]=s(n[i],a):h===b.DEFINE_MANY&&(n[i]=u(n[i],a))}else n[i]=a}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in T;o?m(!1):void 0;var i=n in e;i?m(!1):void 0,e[n]=r}}}function a(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:m(!1);for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]?m(!1):void 0,e[n]=t[n]);return e}function s(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 u(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=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=l(e,o)}}var p=e(179),d=e(34),f=e(64),h=(e(86),e(85),e(83)),v=e(161),m=e(168),g=e(171),y=e(172),C=(e(178),y({mixins:null})),b=g({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),_=[],E={mixins:b.DEFINE_MANY,statics:b.DEFINE_MANY,propTypes:b.DEFINE_MANY,contextTypes:b.DEFINE_MANY,childContextTypes:b.DEFINE_MANY,getDefaultProps:b.DEFINE_MANY_MERGED,getInitialState:b.DEFINE_MANY_MERGED,getChildContext:b.DEFINE_MANY_MERGED,render:b.DEFINE_ONCE,componentWillMount:b.DEFINE_MANY,componentDidMount:b.DEFINE_MANY,componentWillReceiveProps:b.DEFINE_MANY,shouldComponentUpdate:b.DEFINE_ONCE,componentWillUpdate:b.DEFINE_MANY,componentDidUpdate:b.DEFINE_MANY,componentWillUnmount:b.DEFINE_MANY,updateComponent:b.OVERRIDE_BASE},T={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=p({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=p({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=s(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=p({},e.propTypes,t)},statics:function(e,t){i(e,t)},autobind:function(){}},x={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},N=function(){};p(N.prototype,d.prototype,x);var P={createClass:function(e){var t=function(e,t,n){this.__reactAutoBindPairs.length&&c(this),this.props=e,this.context=t,this.refs=v,this.updater=n||h,this.state=null;var r=this.getInitialState?this.getInitialState():null;"object"!=typeof r||Array.isArray(r)?m(!1):void 0,this.state=r};t.prototype=new N,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],_.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:m(!1);for(var n in E)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){_.push(e)}}};t.exports=P},{161:161,168:168,171:171,172:172,178:178,179:179,34:34,64:64,83:83,85:85,86:86}],34:[function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=i,this.updater=n||o}var o=e(83),i=(e(75),e(123),e(161)),a=e(168);e(178);r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?a(!1):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")};t.exports=r},{123:123,161:161,168:168,178:178,75:75,83:83}],35:[function(e,t,n){"use strict";var r=e(7),o=e(50),i={processChildrenUpdates:o.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,unmountIDFromEnvironment:function(e){}};t.exports=i},{50:50,7:7}],36:[function(e,t,n){"use strict";var r=e(168),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkup:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o?r(!1):void 0,i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkup=e.replaceNodeWithMarkup,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};t.exports=i},{168:168}],37:[function(e,t,n){"use strict";var r=e(147),o={shouldComponentUpdate:function(e,t){return r(this,e,t)}};t.exports=o},{147:147}],38:[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""}function o(e){}function i(e,t){}function a(e){return e.prototype&&e.prototype.isReactComponent}var s=e(179),u=e(36),l=e(39),c=e(64),p=e(67),d=e(74),f=(e(75),e(82)),h=e(86),v=(e(85),e(89)),m=e(98),g=e(161),y=e(168),C=e(148);e(178);o.prototype.render=function(){var e=d.get(this)._currentElement.type,t=e(this.props,this.context,this.updater);return i(e,t),t};var b=1,_={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._nativeParent=null,this._nativeContainerInfo=null,this._updateBatchNumber=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedNodeType=null,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null,this._calledComponentWillUnmount=!1},mountComponent:function(e,t,n,r){this._context=r,this._mountOrder=b++,this._nativeParent=t,this._nativeContainerInfo=n;var s,u=this._processProps(this._currentElement.props),l=this._processContext(r),p=this._currentElement.type,f=this._constructComponent(u,l);a(p)||null!=f&&null!=f.render||(s=f,i(p,s),null===f||f===!1||c.isValidElement(f)?void 0:y(!1),f=new o(p)),f.props=u,f.context=l,f.refs=g,f.updater=m,this._instance=f,d.set(f,this);var h=f.state;void 0===h&&(f.state=h=null),"object"!=typeof h||Array.isArray(h)?y(!1):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var v;return v=f.unstable_handleError?this.performInitialMountWithErrorHandling(s,t,n,e,r):this.performInitialMount(s,t,n,e,r),f.componentDidMount&&e.getReactMountReady().enqueue(f.componentDidMount,f),v},_constructComponent:function(e,t){return this._constructComponentWithoutOwner(e,t)},_constructComponentWithoutOwner:function(e,t){var n,r=this._currentElement.type;return n=a(r)?new r(e,t,m):r(e,t,m)},performInitialMountWithErrorHandling:function(e,t,n,r,o){var i,a=r.checkpoint();try{i=this.performInitialMount(e,t,n,r,o)}catch(s){r.rollback(a),this._instance.unstable_handleError(s),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),a=r.checkpoint(),this._renderedComponent.unmountComponent(!0),r.rollback(a),i=this.performInitialMount(e,t,n,r,o)}return i},performInitialMount:function(e,t,n,r,o){var i=this._instance;i.componentWillMount&&(i.componentWillMount(),this._pendingStateQueue&&(i.state=this._processPendingState(i.props,i.context))),void 0===e&&(e=this._renderValidatedComponent()),this._renderedNodeType=f.getType(e),this._renderedComponent=this._instantiateReactComponent(e);var a=v.mountComponent(this._renderedComponent,r,t,n,this._processChildContext(o));return a},getNativeNode:function(){return v.getNativeNode(this._renderedComponent)},unmountComponent:function(e){if(this._renderedComponent){var t=this._instance;if(t.componentWillUnmount&&!t._calledComponentWillUnmount)if(t._calledComponentWillUnmount=!0,e){var n=this.getName()+".componentWillUnmount()";p.invokeGuardedCallback(n,t.componentWillUnmount.bind(t))}else t.componentWillUnmount();this._renderedComponent&&(v.unmountComponent(this._renderedComponent,e),this._renderedNodeType=null,this._renderedComponent=null,this._instance=null),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,d.remove(t)}},_maskContext:function(e){var t=this._currentElement.type,n=t.contextTypes;if(!n)return g;var r={};for(var o in n)r[o]=e[o];return r},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._currentElement.type,n=this._instance,r=n.getChildContext&&n.getChildContext();if(r){"object"!=typeof t.childContextTypes?y(!1):void 0;for(var o in r)o in t.childContextTypes?void 0:y(!1);return s({},e,r)}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{"function"!=typeof e[i]?y(!1):void 0,a=e[i](t,i,o,n)}catch(s){a=s}a instanceof Error&&(r(this),n===h.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?v.receiveComponent(this,this._pendingElement,e,this._context):null!==this._pendingStateQueue||this._pendingForceUpdate?this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context):this._updateBatchNumber=null},updateComponent:function(e,t,n,r,o){var i,a,s=this._instance,u=!1;this._context===o?i=s.context:(i=this._processContext(o),u=!0),t===n?a=n.props:(a=this._processProps(n.props),u=!0),u&&s.componentWillReceiveProps&&s.componentWillReceiveProps(a,i);var l=this._processPendingState(a,i),c=!0;!this._pendingForceUpdate&&s.shouldComponentUpdate&&(c=s.shouldComponentUpdate(a,l,i)),this._updateBatchNumber=null,c?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,a,l,i,e,o)):(this._currentElement=n,this._context=o,s.props=a,s.state=l,s.context=i)},_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=s({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var u=r[a];s(i,"function"==typeof u?u.call(n,i,e,t):u)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a,s,u,l=this._instance,c=Boolean(l.componentDidUpdate);c&&(a=l.props,s=l.state,u=l.context),l.componentWillUpdate&&l.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,l.props=t,l.state=n,l.context=r,this._updateRenderedComponent(o,i),c&&o.getReactMountReady().enqueue(l.componentDidUpdate.bind(l,a,s,u),l)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(C(r,o))v.receiveComponent(n,o,e,this._processChildContext(t));else{var i=v.getNativeNode(n);v.unmountComponent(n,!1),this._renderedNodeType=f.getType(o),this._renderedComponent=this._instantiateReactComponent(o);var a=v.mountComponent(this._renderedComponent,e,this._nativeParent,this._nativeContainerInfo,this._processChildContext(t));this._replaceNodeWithMarkup(i,a,n)}},_replaceNodeWithMarkup:function(e,t,n){u.replaceNodeWithMarkup(e,t,n)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(){var e;l.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{l.current=null}return null===e||e===!1||c.isValidElement(e)?void 0:y(!1),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n?y(!1):void 0;var r=t.getPublicInstance(),o=n.refs===g?n.refs={}:n.refs;o[e]=r},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return e instanceof o?null:e},_instantiateReactComponent:null},E={Mixin:_};t.exports=E},{148:148,161:161,168:168,178:178,179:179,36:36,39:39,64:64,67:67,74:74,75:75,82:82,85:85,86:86,89:89,98:98}],39:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],40:[function(e,t,n){"use strict";var r=e(44),o=e(63),i=e(78),a=e(89),s=e(99),u=e(100),l=e(127),c=e(135),p=e(144);e(178);o.inject();var d={findDOMNode:l,render:i.render,unmountComponentAtNode:i.unmountComponentAtNode,version:u,unstable_batchedUpdates:s.batchedUpdates,unstable_renderSubtreeIntoContainer:p};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ComponentTree:{getClosestInstanceFromNode:r.getClosestInstanceFromNode,getNodeFromInstance:function(e){return e._renderedComponent&&(e=c(e)),e?r.getNodeFromInstance(e):null}},Mount:i,Reconciler:a});t.exports=d},{100:100,127:127,135:135,144:144,178:178,44:44,63:63,78:78,89:89,99:99}],41:[function(e,t,n){"use strict";var r=e(14),o={getNativeProps:r.getNativeProps};t.exports=o},{14:14}],42:[function(e,t,n){"use strict";function r(e,t){t&&(X[e._tag]&&(null!=t.children||null!=t.dangerouslySetInnerHTML?O(!1):void 0),null!=t.dangerouslySetInnerHTML&&(null!=t.children?O(!1):void 0,"object"==typeof t.dangerouslySetInnerHTML&&K in t.dangerouslySetInnerHTML?void 0:O(!1)),null!=t.style&&"object"!=typeof t.style?O(!1):void 0)}function o(e,t,n,r){if(!(r instanceof D)){var o=e._nativeContainerInfo,a=o._node&&o._node.nodeType===H,s=a?o._node:o._ownerDocument;V(t,s),r.getReactMountReady().enqueue(i,{inst:e,registrationName:t,listener:n})}}function i(){var e=this;b.putListener(e.inst,e.registrationName,e.listener)}function a(){var e=this;S.postMountWrapper(e)}function s(){var e=this;e._rootNodeID?void 0:O(!1);var t=F(e);switch(t?void 0:O(!1),e._tag){case"iframe":case"object":e._wrapperState.listeners=[E.trapBubbledEvent(C.topLevelTypes.topLoad,"load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in Y)Y.hasOwnProperty(n)&&e._wrapperState.listeners.push(E.trapBubbledEvent(C.topLevelTypes[n],Y[n],t));break;case"img":e._wrapperState.listeners=[E.trapBubbledEvent(C.topLevelTypes.topError,"error",t),E.trapBubbledEvent(C.topLevelTypes.topLoad,"load",t)];break;case"form":e._wrapperState.listeners=[E.trapBubbledEvent(C.topLevelTypes.topReset,"reset",t),E.trapBubbledEvent(C.topLevelTypes.topSubmit,"submit",t)];break;case"input":case"select":case"textarea":e._wrapperState.listeners=[E.trapBubbledEvent(C.topLevelTypes.topInvalid,"invalid",t)]}}function u(){M.postUpdateWrapper(this)}function l(e){Z.call($,e)||(Q.test(e)?void 0:O(!1),$[e]=!0)}function c(e,t){return e.indexOf("-")>=0||null!=t.is}function p(e){var t=e.type;l(t),this._currentElement=e,this._tag=t.toLowerCase(),this._namespaceURI=null,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._nativeNode=null,this._nativeParent=null,this._rootNodeID=null,this._domID=null,this._nativeContainerInfo=null,this._wrapperState=null,this._topLevelWrapper=null,this._flags=0}var d=e(179),f=e(1),h=e(4),v=e(8),m=e(9),g=e(10),y=e(11),C=e(16),b=e(17),_=e(18),E=e(28),T=e(35),x=e(41),N=e(43),P=e(44),w=e(51),S=e(53),M=e(54),k=e(58),R=(e(75),e(79)),D=e(93),A=(e(160),e(126)),O=e(168),I=(e(140),e(172)),L=(e(177),e(151),e(178),N),U=b.deleteListener,F=P.getNodeFromInstance,V=E.listenTo,B=_.registrationNameModules,j={string:!0,number:!0},W=I({style:null}),K=I({__html:null}),q={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},H=11,Y={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},z={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},G={listing:!0,pre:!0,textarea:!0},X=d({menuitem:!0},z),Q=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,$={},Z={}.hasOwnProperty,J=1;p.displayName="ReactDOMComponent",p.Mixin={mountComponent:function(e,t,n,o){this._rootNodeID=J++,this._domID=n._idCounter++,this._nativeParent=t,this._nativeContainerInfo=n;var i=this._currentElement.props;switch(this._tag){case"iframe":case"object":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},e.getReactMountReady().enqueue(s,this);break;case"button":i=x.getNativeProps(this,i,t);break;case"input":w.mountWrapper(this,i,t),i=w.getNativeProps(this,i),e.getReactMountReady().enqueue(s,this);break;case"option":S.mountWrapper(this,i,t),i=S.getNativeProps(this,i);break;case"select":M.mountWrapper(this,i,t),i=M.getNativeProps(this,i),e.getReactMountReady().enqueue(s,this);break;case"textarea":k.mountWrapper(this,i,t),i=k.getNativeProps(this,i),e.getReactMountReady().enqueue(s,this)}r(this,i);var u,l;null!=t?(u=t._namespaceURI,l=t._tag):n._tag&&(u=n._namespaceURI,l=n._tag),(null==u||u===m.svg&&"foreignobject"===l)&&(u=m.html),u===m.html&&("svg"===this._tag?u=m.svg:"math"===this._tag&&(u=m.mathml)),this._namespaceURI=u;var c;if(e.useCreateElement){var p,d=n._ownerDocument;if(u===m.html)if("script"===this._tag){var h=d.createElement("div"),g=this._currentElement.type;h.innerHTML="<"+g+"></"+g+">",p=h.removeChild(h.firstChild)}else p=d.createElement(this._currentElement.type,i.is||null);else p=d.createElementNS(u,this._currentElement.type);P.precacheNode(this,p),this._flags|=L.hasCachedChildNodes,this._nativeParent||y.setAttributeForRoot(p),this._updateDOMProperties(null,i,e);var C=v(p);this._createInitialChildren(e,i,o,C),c=C}else{var b=this._createOpenTagMarkupAndPutListeners(e,i),_=this._createContentMarkup(e,i,o);c=!_&&z[this._tag]?b+"/>":b+">"+_+"</"+this._currentElement.type+">"}switch(this._tag){case"button":case"input":case"select":case"textarea":i.autoFocus&&e.getReactMountReady().enqueue(f.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(a,this)}return c},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var i=t[r];if(null!=i)if(B.hasOwnProperty(r))i&&o(this,r,i,e);else{r===W&&(i&&(i=this._previousStyleCopy=d({},t.style)),i=h.createMarkupForStyles(i,this));var a=null;null!=this._tag&&c(this._tag,t)?q.hasOwnProperty(r)||(a=y.createMarkupForCustomAttribute(r,i)):a=y.createMarkupForProperty(r,i),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._nativeParent||(n+=" "+y.createMarkupForRoot()),n+=" "+y.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=j[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=A(i);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return G[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&v.queueHTML(r,o.__html);else{var i=j[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)v.queueText(r,i);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u<s.length;u++)v.queueChild(r,s[u])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,o){var i=t.props,a=this._currentElement.props;switch(this._tag){case"button":i=x.getNativeProps(this,i),a=x.getNativeProps(this,a);break;case"input":w.updateWrapper(this),i=w.getNativeProps(this,i),a=w.getNativeProps(this,a);break;case"option":i=S.getNativeProps(this,i),a=S.getNativeProps(this,a);break;case"select":i=M.getNativeProps(this,i),a=M.getNativeProps(this,a);break;case"textarea":k.updateWrapper(this),i=k.getNativeProps(this,i),a=k.getNativeProps(this,a)}r(this,a),this._updateDOMProperties(i,a,e),this._updateDOMChildren(i,a,e,o),"select"===this._tag&&e.getReactMountReady().enqueue(u,this)},_updateDOMProperties:function(e,t,n){var r,i,a;for(r in e)if(!t.hasOwnProperty(r)&&e.hasOwnProperty(r)&&null!=e[r])if(r===W){var s=this._previousStyleCopy;for(i in s)s.hasOwnProperty(i)&&(a=a||{},a[i]="");this._previousStyleCopy=null}else B.hasOwnProperty(r)?e[r]&&U(this,r):(g.properties[r]||g.isCustomAttribute(r))&&y.deleteValueForProperty(F(this),r);for(r in t){var u=t[r],l=r===W?this._previousStyleCopy:null!=e?e[r]:void 0;if(t.hasOwnProperty(r)&&u!==l&&(null!=u||null!=l))if(r===W)if(u?u=this._previousStyleCopy=d({},u):this._previousStyleCopy=null,l){for(i in l)!l.hasOwnProperty(i)||u&&u.hasOwnProperty(i)||(a=a||{},a[i]="");for(i in u)u.hasOwnProperty(i)&&l[i]!==u[i]&&(a=a||{},a[i]=u[i])}else a=u;else if(B.hasOwnProperty(r))u?o(this,r,u,n):l&&U(this,r);else if(c(this._tag,t))q.hasOwnProperty(r)||y.setValueForAttribute(F(this),r,u);else if(g.properties[r]||g.isCustomAttribute(r)){var p=F(this);null!=u?y.setValueForProperty(p,r,u):y.deleteValueForProperty(p,r)}}a&&h.setValueForStyles(F(this),a,this)},_updateDOMChildren:function(e,t,n,r){var o=j[typeof e.children]?e.children:null,i=j[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,u=null!=o?null:e.children,l=null!=i?null:t.children,c=null!=o||null!=a,p=null!=i||null!=s;null!=u&&null==l?this.updateChildren(null,n,r):c&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=s?a!==s&&this.updateMarkup(""+s):null!=l&&this.updateChildren(l,n,r)},getNativeNode:function(){return F(this)},unmountComponent:function(e){switch(this._tag){case"iframe":case"object":case"img":case"form":case"video":
case"audio":var t=this._wrapperState.listeners;if(t)for(var n=0;n<t.length;n++)t[n].remove();break;case"html":case"head":case"body":O(!1)}this.unmountChildren(e),P.uncacheNode(this),b.deleteAllListeners(this),T.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._domID=null,this._wrapperState=null},getPublicInstance:function(){return F(this)}},d(p.prototype,p.Mixin,R.Mixin),t.exports=p},{1:1,10:10,11:11,126:126,140:140,151:151,16:16,160:160,168:168,17:17,172:172,177:177,178:178,179:179,18:18,28:28,35:35,4:4,41:41,43:43,44:44,51:51,53:53,54:54,58:58,75:75,79:79,8:8,9:9,93:93}],43:[function(e,t,n){"use strict";var r={hasCachedChildNodes:1};t.exports=r},{}],44:[function(e,t,n){"use strict";function r(e){for(var t;t=e._renderedComponent;)e=t;return e}function o(e,t){var n=r(e);n._nativeNode=t,t[v]=n}function i(e){var t=e._nativeNode;t&&(delete t[v],e._nativeNode=null)}function a(e,t){if(!(e._flags&h.hasCachedChildNodes)){var n=e._renderedChildren,i=t.firstChild;e:for(var a in n)if(n.hasOwnProperty(a)){var s=n[a],u=r(s)._domID;if(null!=u){for(;null!==i;i=i.nextSibling)if(1===i.nodeType&&i.getAttribute(f)===String(u)||8===i.nodeType&&i.nodeValue===" react-text: "+u+" "||8===i.nodeType&&i.nodeValue===" react-empty: "+u+" "){o(s,i);continue e}d(!1)}}e._flags|=h.hasCachedChildNodes}}function s(e){if(e[v])return e[v];for(var t=[];!e[v];){if(t.push(e),!e.parentNode)return null;e=e.parentNode}for(var n,r;e&&(r=e[v]);e=t.pop())n=r,t.length&&a(r,e);return n}function u(e){var t=s(e);return null!=t&&t._nativeNode===e?t:null}function l(e){if(void 0===e._nativeNode?d(!1):void 0,e._nativeNode)return e._nativeNode;for(var t=[];!e._nativeNode;)t.push(e),e._nativeParent?void 0:d(!1),e=e._nativeParent;for(;t.length;e=t.pop())a(e,e._nativeNode);return e._nativeNode}var c=e(10),p=e(43),d=e(168),f=c.ID_ATTRIBUTE_NAME,h=p,v="__reactInternalInstance$"+Math.random().toString(36).slice(2),m={getClosestInstanceFromNode:s,getInstanceFromNode:u,getNodeFromInstance:l,precacheChildNodes:a,precacheNode:o,uncacheNode:i};t.exports=m},{10:10,168:168,43:43}],45:[function(e,t,n){"use strict";function r(e,t){var n={_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?t.nodeType===o?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null};return n}var o=(e(151),9);t.exports=r},{151:151}],46:[function(e,t,n){"use strict";function r(e,t,n,r,o,i){}var o=e(60),i=(e(178),[]),a={addDevtool:function(e){i.push(e)},removeDevtool:function(e){for(var t=0;t<i.length;t++)i[t]===e&&(i.splice(t,1),t--)},onCreateMarkupForProperty:function(e,t){r("onCreateMarkupForProperty",e,t)},onSetValueForProperty:function(e,t,n){r("onSetValueForProperty",e,t,n)},onDeleteValueForProperty:function(e,t){r("onDeleteValueForProperty",e,t)}};a.addDevtool(o),t.exports=a},{178:178,60:60}],47:[function(e,t,n){"use strict";var r=e(179),o=e(8),i=e(44),a=function(e){this._currentElement=null,this._nativeNode=null,this._nativeParent=null,this._nativeContainerInfo=null,this._domID=null};r(a.prototype,{mountComponent:function(e,t,n,r){var a=n._idCounter++;this._domID=a,this._nativeParent=t,this._nativeContainerInfo=n;var s=" react-empty: "+this._domID+" ";if(e.useCreateElement){var u=n._ownerDocument,l=u.createComment(s);return i.precacheNode(this,l),o(l)}return e.renderToStaticMarkup?"":"<!--"+s+"-->"},receiveComponent:function(){},getNativeNode:function(){return i.getNodeFromInstance(this)},unmountComponent:function(){i.uncacheNode(this)}}),t.exports=a},{179:179,44:44,8:8}],48:[function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=e(64),i=(e(65),e(173)),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",image:"image",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},{173:173,64:64,65:65}],49:[function(e,t,n){"use strict";var r={useCreateElement:!0};t.exports=r},{}],50:[function(e,t,n){"use strict";var r=e(7),o=e(44),i={dangerouslyProcessChildrenUpdates:function(e,t){var n=o.getNodeFromInstance(e);r.processUpdates(n,t)}};t.exports=i},{44:44,7:7}],51:[function(e,t,n){"use strict";function r(){this._rootNodeID&&d.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=u.executeOnChange(t,e);c.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var i=l.getNodeFromInstance(this),a=i;a.parentNode;)a=a.parentNode;for(var s=a.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),d=0;d<s.length;d++){var f=s[d];if(f!==i&&f.form===i.form){var h=l.getInstanceFromNode(f);h?void 0:p(!1),c.asap(r,h)}}}return n}var i=e(179),a=e(14),s=e(11),u=e(25),l=e(44),c=e(99),p=e(168),d=(e(178),{getNativeProps:function(e,t){var n=u.getValue(t),r=u.getChecked(t),o=i({type:void 0},a.getNativeProps(e,t),{defaultChecked:void 0,defaultValue:void 0,value:null!=n?n:e._wrapperState.initialValue,checked:null!=r?r:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange});return o},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:t.defaultChecked||!1,initialValue:null!=n?n:null,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&s.setValueForProperty(l.getNodeFromInstance(e),"checked",n||!1);var r=u.getValue(t);null!=r&&s.setValueForProperty(l.getNodeFromInstance(e),"value",""+r)}});t.exports=d},{11:11,14:14,168:168,178:178,179:179,25:25,44:44,99:99}],52:[function(e,t,n){"use strict";var r=e(46);t.exports={debugTool:r}},{46:46}],53:[function(e,t,n){"use strict";var r=e(179),o=e(32),i=e(44),a=e(54),s=(e(178),{mountWrapper:function(e,t,n){var r=null;if(null!=n){var o=n;"optgroup"===o._tag&&(o=o._nativeParent),null!=o&&"select"===o._tag&&(r=a.getSelectValueContext(o))}var i=null;if(null!=r)if(i=!1,Array.isArray(r)){for(var s=0;s<r.length;s++)if(""+r[s]==""+t.value){i=!0;break}}else i=""+r==""+t.value;e._wrapperState={selected:i}},postMountWrapper:function(e){var t=e._currentElement.props;if(null!=t.value){var n=i.getNodeFromInstance(e);n.setAttribute("value",t.value)}},getNativeProps:function(e,t){var n=r({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var i="";return o.forEach(t.children,function(e){null!=e&&("string"!=typeof e&&"number"!=typeof e||(i+=e))}),i&&(n.children=i),n}});t.exports=s},{178:178,179:179,32:32,44:44,54:54}],54:[function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=u.getValue(e);null!=t&&o(this,Boolean(e.multiple),t)}}function o(e,t,n){var r,o,i=l.getNodeFromInstance(e).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<i.length;o++){var a=r.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(r=""+n,o=0;o<i.length;o++)if(i[o].value===r)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}function i(e){var t=this._currentElement.props,n=u.executeOnChange(t,e);return this._rootNodeID&&(this._wrapperState.pendingUpdate=!0),c.asap(r,this),n}var a=e(179),s=e(14),u=e(25),l=e(44),c=e(99),p=(e(178),!1),d={getNativeProps:function(e,t){return a({},s.getNativeProps(e,t),{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=u.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,listeners:null,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)},void 0===t.value||void 0===t.defaultValue||p||(p=!0)},getSelectValueContext:function(e){return e._wrapperState.initialValue},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=u.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};t.exports=d},{14:14,178:178,179:179,25:25,44:44,99:99}],55:[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,s=t.getRangeAt(0);try{s.startContainer.nodeType,s.endContainer.nodeType}catch(u){return null}var l=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=l?0:s.toString().length,p=s.cloneRange();p.selectNodeContents(e),p.setEnd(s.startContainer,s.startOffset);var d=r(p.startContainer,p.startOffset,p.endContainer,p.endOffset),f=d?0:p.toString().length,h=f+c,v=document.createRange();v.setStart(n,o),v.setEnd(i,a);var m=v.collapsed;return{start:m?h:f,end:m?f:h}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();void 0===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 s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i=void 0===t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var s=l(e,o),u=l(e,i);if(s&&u){var p=document.createRange();p.setStart(s.node,s.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(u.node,u.offset)):(p.setEnd(u.node,u.offset),n.addRange(p))}}}var u=e(154),l=e(136),c=e(137),p=u.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:i,setOffsets:p?a:s};t.exports=d},{136:136,137:137,154:154}],56:[function(e,t,n){"use strict";var r=e(63),o=e(92),i=e(100);r.inject();var a={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:i};t.exports=a},{100:100,63:63,92:92}],57:[function(e,t,n){"use strict";var r=e(179),o=e(7),i=e(8),a=e(44),s=(e(75),e(126)),u=e(168),l=(e(151),function(e){this._currentElement=e,this._stringText=""+e,this._nativeNode=null,this._nativeParent=null,this._domID=null,this._mountIndex=0,this._closingComment=null,this._commentNodes=null});r(l.prototype,{mountComponent:function(e,t,n,r){var o=n._idCounter++,u=" react-text: "+o+" ",l=" /react-text ";if(this._domID=o,this._nativeParent=t,e.useCreateElement){var c=n._ownerDocument,p=c.createComment(u),d=c.createComment(l),f=i(c.createDocumentFragment());return i.queueChild(f,i(p)),this._stringText&&i.queueChild(f,i(c.createTextNode(this._stringText))),i.queueChild(f,i(d)),a.precacheNode(this,p),this._closingComment=d,f}var h=s(this._stringText);return e.renderToStaticMarkup?h:"<!--"+u+"-->"+h+"<!--"+l+"-->"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=this.getNativeNode();o.replaceDelimitedText(r[0],r[1],n)}}},getNativeNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=a.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n?u(!1):void 0,8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._nativeNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,a.uncacheNode(this)}}),t.exports=l},{126:126,151:151,168:168,179:179,44:44,7:7,75:75,8:8}],58:[function(e,t,n){"use strict";function r(){this._rootNodeID&&d.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=u.executeOnChange(t,e);return c.asap(r,this),n}var i=e(179),a=e(14),s=e(11),u=e(25),l=e(44),c=e(99),p=e(168),d=(e(178),{getNativeProps:function(e,t){null!=t.dangerouslySetInnerHTML?p(!1):void 0;var n=i({},a.getNativeProps(e,t),{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return n},mountWrapper:function(e,t){var n=t.defaultValue,r=t.children;null!=r&&(null!=n?p(!1):void 0,Array.isArray(r)&&(r.length<=1?void 0:p(!1),r=r[0]),n=""+r),null==n&&(n="");var i=u.getValue(t);e._wrapperState={initialValue:""+(null!=i?i:n),listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=u.getValue(t);null!=n&&s.setValueForProperty(l.getNodeFromInstance(e),"value",""+n)}});t.exports=d},{11:11,14:14,168:168,178:178,179:179,25:25,44:44,99:99}],59:[function(e,t,n){"use strict";function r(e,t){"_nativeNode"in e?void 0:u(!1),"_nativeNode"in t?void 0:u(!1);for(var n=0,r=e;r;r=r._nativeParent)n++;for(var o=0,i=t;i;i=i._nativeParent)o++;for(;n-o>0;)e=e._nativeParent,n--;for(;o-n>0;)t=t._nativeParent,o--;for(var a=n;a--;){if(e===t)return e;e=e._nativeParent,t=t._nativeParent}return null}function o(e,t){"_nativeNode"in e?void 0:u(!1),"_nativeNode"in t?void 0:u(!1);for(;t;){if(t===e)return!0;t=t._nativeParent}return!1}function i(e){return"_nativeNode"in e?void 0:u(!1),e._nativeParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._nativeParent;var o;for(o=r.length;o-- >0;)t(r[o],!1,n);for(o=0;o<r.length;o++)t(r[o],!0,n)}function s(e,t,n,o,i){for(var a=e&&t?r(e,t):null,s=[];e&&e!==a;)s.push(e),e=e._nativeParent;for(var u=[];t&&t!==a;)u.push(t),t=t._nativeParent;var l;for(l=0;l<s.length;l++)n(s[l],!0,o);for(l=u.length;l-- >0;)n(u[l],!1,i)}var u=e(168);t.exports={isAncestor:o,getLowestCommonAncestor:r,getParentInstance:i,traverseTwoPhase:a,traverseEnterLeave:s}},{168:168}],60:[function(e,t,n){"use strict";var r,o=(e(10),e(18),e(178),{onCreateMarkupForProperty:function(e,t){r(e)},onSetValueForProperty:function(e,t,n){r(t)},onDeleteValueForProperty:function(e,t){r(t)}});t.exports=o},{10:10,178:178,18:18}],61:[function(e,t,n){"use strict";function r(e,t,n,r,o,i){}function o(e){}var i=(e(154),e(176),e(178),[]),a={addDevtool:function(e){i.push(e)},removeDevtool:function(e){for(var t=0;t<i.length;t++)i[t]===e&&(i.splice(t,1),t--)},beginProfiling:function(){},endProfiling:function(){},getFlushHistory:function(){},onBeginFlush:function(){r("onBeginFlush")},onEndFlush:function(){r("onEndFlush")},onBeginLifeCycleTimer:function(e,t){o(e),r("onBeginLifeCycleTimer",e,t)},onEndLifeCycleTimer:function(e,t){o(e),r("onEndLifeCycleTimer",e,t)},onBeginReconcilerTimer:function(e,t){o(e),r("onBeginReconcilerTimer",e,t)},onEndReconcilerTimer:function(e,t){o(e),r("onEndReconcilerTimer",e,t)},onBeginProcessingChildContext:function(){r("onBeginProcessingChildContext")},onEndProcessingChildContext:function(){r("onEndProcessingChildContext")},onNativeOperation:function(e,t,n){o(e),r("onNativeOperation",e,t,n)},onSetState:function(){r("onSetState")},onSetDisplayName:function(e,t){o(e),r("onSetDisplayName",e,t)},onSetChildren:function(e,t){o(e),r("onSetChildren",e,t)},onSetOwner:function(e,t){o(e),r("onSetOwner",e,t)},onSetText:function(e,t){o(e),r("onSetText",e,t)},onMountRootComponent:function(e){o(e),r("onMountRootComponent",e)},onMountComponent:function(e){o(e),r("onMountComponent",e)},onUpdateComponent:function(e){o(e),r("onUpdateComponent",e)},onUnmountComponent:function(e){o(e),r("onUnmountComponent",e)}};t.exports=a},{154:154,176:176,178:178}],62:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=e(179),i=e(99),a=e(119),s=e(160),u={initialize:s,close:function(){d.isBatchingUpdates=!1}},l={initialize:s,close:i.flushBatchedUpdates.bind(i)},c=[l,u];o(r.prototype,a.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},{119:119,160:160,179:179,99:99}],63:[function(e,t,n){"use strict";function r(){E||(E=!0,g.EventEmitter.injectReactEventListener(m),g.EventPluginHub.injectEventPluginOrder(a),g.EventPluginUtils.injectComponentTree(p),g.EventPluginUtils.injectTreeTraversal(f),g.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:_,EnterLeaveEventPlugin:s,ChangeEventPlugin:i,SelectEventPlugin:b,BeforeInputEventPlugin:o}),g.NativeComponent.injectGenericComponentClass(c),g.NativeComponent.injectTextComponentClass(h),g.DOMProperty.injectDOMPropertyConfig(u),g.DOMProperty.injectDOMPropertyConfig(C),g.EmptyComponent.injectEmptyComponentFactory(function(e){return new d(e)}),g.Updates.injectReconcileTransaction(y),g.Updates.injectBatchingStrategy(v),g.Component.injectEnvironment(l))}var o=e(2),i=e(6),a=e(13),s=e(15),u=e(22),l=e(35),c=e(42),p=e(44),d=e(47),f=e(59),h=e(57),v=e(62),m=e(69),g=e(72),y=e(88),C=e(103),b=e(104),_=e(105),E=!1;t.exports={inject:r}},{103:103,104:104,105:105,13:13,15:15,2:2,22:22,35:35,42:42,44:44,47:47,57:57,59:59,6:6,62:62,69:69,72:72,88:88}],64:[function(e,t,n){"use strict";var r=e(179),o=e(39),i=(e(178),e(123),"function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103),a={key:!0,ref:!0,__self:!0,__source:!0},s=function(e,t,n,r,o,a,s){var u={$$typeof:i,type:e,key:t,ref:n,props:s,_owner:a};return u};s.createElement=function(e,t,n){var r,i={},u=null,l=null,c=null,p=null;if(null!=t){l=void 0===t.ref?null:t.ref,u=void 0===t.key?null:""+t.key,c=void 0===t.__self?null:t.__self,p=void 0===t.__source?null:t.__source;for(r in t)t.hasOwnProperty(r)&&!a.hasOwnProperty(r)&&(i[r]=t[r])}var d=arguments.length-2;if(1===d)i.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];i.children=f}if(e&&e.defaultProps){var v=e.defaultProps;for(r in v)void 0===i[r]&&(i[r]=v[r])}return s(e,u,l,c,p,o.current,i)},s.createFactory=function(e){var t=s.createElement.bind(null,e);return t.type=e,t},s.cloneAndReplaceKey=function(e,t){var n=s(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},s.cloneElement=function(e,t,n){var i,u=r({},e.props),l=e.key,c=e.ref,p=e._self,d=e._source,f=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,f=o.current),void 0!==t.key&&(l=""+t.key);var h;e.type&&e.type.defaultProps&&(h=e.type.defaultProps);for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(void 0===t[i]&&void 0!==h?u[i]=h[i]:u[i]=t[i])}var v=arguments.length-2;if(1===v)u.children=n;else if(v>1){for(var m=Array(v),g=0;v>g;g++)m[g]=arguments[g+2];u.children=m}return s(e.type,l,c,p,d,f,u)},s.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===i},t.exports=s},{123:123,178:178,179:179,39:39}],65:[function(e,t,n){"use strict";function r(){if(p.current){var e=p.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e,t){e._store&&!e._store.validated&&null==e.key&&(e._store.validated=!0,i("uniqueKey",e,t))}function i(e,t,n){var o=r();if(!o){var i="string"==typeof n?n:n.displayName||n.name;i&&(o=" Check the top-level render call using <"+i+">.")}var a=h[e]||(h[e]={});if(a[o])return null;a[o]=!0;var s={parentOrOwner:o,url:" See https://fb.me/react-warning-keys for more information.",childOwner:null};return t&&t._owner&&t._owner!==p.current&&(s.childOwner=" It was passed a child from "+t._owner.getName()+"."),s}function a(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];l.isValidElement(r)&&o(r,t)}else if(l.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var i=d(e);if(i&&i!==e.entries)for(var a,s=i.call(e);!(a=s.next()).done;)l.isValidElement(a.value)&&o(a.value,t)}}function s(e,t,n,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{"function"!=typeof t[i]?f(!1):void 0,a=t[i](n,i,e,o)}catch(s){a=s}a instanceof Error&&!(a.message in v)&&(v[a.message]=!0,r())}}function u(e){var t=e.type;if("function"==typeof t){var n=t.displayName||t.name;t.propTypes&&s(n,t.propTypes,e.props,c.prop),"function"==typeof t.getDefaultProps}}var l=e(64),c=e(86),p=(e(85),e(39)),d=(e(123),e(134)),f=e(168),h=(e(178),{}),v={},m={createElement:function(e,t,n){var r="string"==typeof e||"function"==typeof e,o=l.createElement.apply(this,arguments);if(null==o)return o;if(r)for(var i=2;i<arguments.length;i++)a(arguments[i],e);return u(o),o},createFactory:function(e){var t=m.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=l.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)a(arguments[o],r.type);return u(r),r}};t.exports=m},{123:123,134:134,168:168,178:178,39:39,64:64,85:85,86:86}],66:[function(e,t,n){"use strict";var r,o={injectEmptyComponentFactory:function(e){r=e}},i={create:function(e){return r(e)}};i.injection=o,t.exports=i},{}],67:[function(e,t,n){"use strict";function r(e,t,n,r){try{return t(n,r)}catch(i){return void(null===o&&(o=i))}}var o=null,i={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};t.exports=i},{}],68:[function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}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}],69:[function(e,t,n){"use strict";function r(e){for(;e._nativeParent;)e=e._nativeParent;var t=p.getNodeFromInstance(e),n=t.parentNode;return p.getClosestInstanceFromNode(n)}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){var t=f(e.nativeEvent),n=p.getClosestInstanceFromNode(t),o=n;do e.ancestors.push(o),o=o&&r(o);while(o);for(var i=0;i<e.ancestors.length;i++)n=e.ancestors[i],v._handleTopLevel(e.topLevelType,n,e.nativeEvent,f(e.nativeEvent))}function a(e){var t=h(window);e(t)}var s=e(179),u=e(153),l=e(154),c=e(26),p=e(44),d=e(99),f=e(133),h=e(165);s(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),c.addPoolingTo(o,c.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:l.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},{133:133,153:153,154:154,165:165,179:179,26:26,44:44,99:99}],70:[function(e,t,n){"use strict";var r={logTopLevelRenders:!1};t.exports=r},{}],71:[function(e,t,n){"use strict";var r=e(32),o=e(64),i=e(160),a=e(168),s=(e(178),{create:function(e){if("object"!=typeof e||!e||Array.isArray(e))return e;if(o.isValidElement(e))return e;1===e.nodeType?a(!1):void 0;var t=[];for(var n in e)r.mapIntoWithKeyPrefixInternal(e[n],t,n,i.thatReturnsArgument);return t}});t.exports=s},{160:160,168:168,178:178,32:32,64:64}],72:[function(e,t,n){"use strict";var r=e(10),o=e(17),i=e(19),a=e(36),s=e(33),u=e(66),l=e(28),c=e(81),p=e(99),d={Component:a.injection,Class:s.injection,DOMProperty:r.injection,EmptyComponent:u.injection,EventPluginHub:o.injection,EventPluginUtils:i.injection,EventEmitter:l.injection,NativeComponent:c.injection,Updates:p.injection};t.exports=d},{10:10,17:17,19:19,28:28,33:33,36:36,66:66,81:81,99:99}],73:[function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=e(55),i=e(157),a=e(162),s=e(163),u={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:u.hasSelectionCapabilities(e)?u.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(u.hasSelectionCapabilities(n)&&u.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&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if(void 0===r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};t.exports=u},{157:157,162:162,163:163,55:55}],74:[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},{}],75:[function(e,t,n){"use strict";var r=e(61);t.exports={debugTool:r}},{61:61}],76:[function(e,t,n){"use strict";function r(e,t){this.value=e,this.requestChange=t}function o(e){var t={value:void 0===e?i.PropTypes.any.isRequired:e.isRequired,requestChange:i.PropTypes.func.isRequired};return i.PropTypes.shape(t)}var i=e(27);r.PropTypes={link:o},t.exports=r},{27:27}],77:[function(e,t,n){"use strict";var r=e(122),o=/\/?>/,i=/^<\!\-\-/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return i.test(e)?e:e.replace(o," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var o=r(e);return o===n}};t.exports=a},{122:122}],78:[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===D?e.documentElement:e.firstChild:null}function i(e){return e.getAttribute&&e.getAttribute(M)||""}function a(e,t,n,r,o){var i;if(C.logTopLevelRenders){var a=e._currentElement.props,s=a.type;i="React mount: "+("string"==typeof s?s:s.displayName||s.name),console.time(i)}var u=_.mountComponent(e,n,null,m(e,t),o);i&&console.timeEnd(i),e._renderedComponent._topLevelWrapper=e,U._mountImageIntoNode(u,t,e,r,n)}function s(e,t,n,r){var o=T.ReactReconcileTransaction.getPooled(!n&&g.useCreateElement);o.perform(a,null,e,t,o,n,r),T.ReactReconcileTransaction.release(o)}function u(e,t,n){for(_.unmountComponent(e,n),t.nodeType===D&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function l(e){var t=o(e);if(t){var n=v.getInstanceFromNode(t);return!(!n||!n._nativeParent)}}function c(e){var t=o(e),n=t&&v.getInstanceFromNode(t);return n&&!n._nativeParent?n:null}function p(e){var t=c(e);return t?t._nativeContainerInfo._topLevelWrapper:null}var d=e(8),f=e(10),h=e(28),v=(e(39),e(44)),m=e(45),g=e(49),y=e(64),C=e(70),b=(e(75),e(77)),_=e(89),E=e(98),T=e(99),x=e(161),N=e(139),P=e(168),w=e(145),S=e(148),M=(e(178),f.ID_ATTRIBUTE_NAME),k=f.ROOT_ATTRIBUTE_NAME,R=1,D=9,A=11,O={},I=1,L=function(){this.rootID=I++};L.prototype.isReactComponent={},L.prototype.render=function(){return this.props};var U={TopLevelWrapper:L,_instancesByReactRootID:O,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return U.scrollMonitor(n,function(){E.enqueueElementInternal(e,t),r&&E.enqueueCallbackInternal(e,r)}),e},_renderNewRootComponent:function(e,t,n,r){!t||t.nodeType!==R&&t.nodeType!==D&&t.nodeType!==A?P(!1):void 0,h.ensureScrollValueMonitoring();var o=N(e);T.batchedUpdates(s,o,t,n,r);var i=o._instance.rootID;return O[i]=o,o},renderSubtreeIntoContainer:function(e,t,n,r){return null==e||null==e._reactInternalInstance?P(!1):void 0,U._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){E.validateCallback(r,"ReactDOM.render"),y.isValidElement(t)?void 0:P(!1);var a=y(L,null,null,null,null,null,t),s=p(n);if(s){var u=s._currentElement,c=u.props;if(S(c,t)){var d=s._renderedComponent.getPublicInstance(),f=r&&function(){r.call(d)};return U._updateRootComponent(s,a,n,f),d}U.unmountComponentAtNode(n)}var h=o(n),v=h&&!!i(h),m=l(n),g=v&&!s&&!m,C=U._renderNewRootComponent(a,n,g,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):x)._renderedComponent.getPublicInstance();return r&&r.call(C),C},render:function(e,t,n){return U._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){!e||e.nodeType!==R&&e.nodeType!==D&&e.nodeType!==A?P(!1):void 0;var t=p(e);return t?(delete O[t._instance.rootID],T.batchedUpdates(u,t,e,!1),!0):(l(e),1===e.nodeType&&e.hasAttribute(k),!1)},_mountImageIntoNode:function(e,t,n,i,a){if(!t||t.nodeType!==R&&t.nodeType!==D&&t.nodeType!==A?P(!1):void 0,i){var s=o(t);if(b.canReuseMarkup(e,s))return void v.precacheNode(n,s);var u=s.getAttribute(b.CHECKSUM_ATTR_NAME);s.removeAttribute(b.CHECKSUM_ATTR_NAME);var l=s.outerHTML;s.setAttribute(b.CHECKSUM_ATTR_NAME,u);var c=e,p=r(c,l);" (client) "+c.substring(p-20,p+20)+"\n (server) "+l.substring(p-20,p+20),t.nodeType===D?P(!1):void 0}if(t.nodeType===D?P(!1):void 0,a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);d.insertTreeBefore(t,e,null)}else w(t,e),v.precacheNode(n,t.firstChild)}};t.exports=U},{10:10,139:139,145:145,148:148,161:161,168:168,178:178,28:28,39:39,44:44,45:45,49:49,64:64,70:70,75:75,77:77,8:8,89:89,98:98,99:99}],79:[function(e,t,n){"use strict";function r(e,t,n){return{type:p.INSERT_MARKUP,content:e,fromIndex:null,fromNode:null,toIndex:n,afterNode:t}}function o(e,t,n){return{type:p.MOVE_EXISTING,content:null,fromIndex:e._mountIndex,fromNode:d.getNativeNode(e),toIndex:n,afterNode:t}}function i(e,t){return{type:p.REMOVE_NODE,content:null,fromIndex:e._mountIndex,fromNode:t,toIndex:null,afterNode:null}}function a(e){return{type:p.SET_MARKUP,content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function s(e){return{type:p.TEXT_CONTENT,content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function u(e,t){return t&&(e=e||[],e.push(t)),e}function l(e,t){c.processChildrenUpdates(e,t)}var c=e(36),p=(e(75),e(80)),d=(e(39),e(89)),f=e(31),h=(e(160),e(128)),v=e(168),m={Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return f.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r,o){var i;return i=h(t),f.updateChildren(e,i,n,r,o),i},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=d.mountComponent(s,t,this,this._nativeContainerInfo,n);s._mountIndex=i++,o.push(u)}return o;
},updateTextContent:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&v(!1);var r=[s(e)];l(this,r)},updateMarkup:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&v(!1);var r=[a(e)];l(this,r)},updateChildren:function(e,t,n){this._updateChildren(e,t,n)},_updateChildren:function(e,t,n){var r=this._renderedChildren,o={},i=this._reconcilerUpdateChildren(r,e,o,t,n);if(i||r){var a,s=null,c=0,p=0,f=null;for(a in i)if(i.hasOwnProperty(a)){var h=r&&r[a],v=i[a];h===v?(s=u(s,this.moveChild(h,f,p,c)),c=Math.max(h._mountIndex,c),h._mountIndex=p):(h&&(c=Math.max(h._mountIndex,c)),s=u(s,this._mountChildAtIndex(v,f,p,t,n))),p++,f=d.getNativeNode(v)}for(a in o)o.hasOwnProperty(a)&&(s=u(s,this._unmountChild(r[a],o[a])));s&&l(this,s),this._renderedChildren=i}},unmountChildren:function(e){var t=this._renderedChildren;f.unmountChildren(t,e),this._renderedChildren=null},moveChild:function(e,t,n,r){return e._mountIndex<r?o(e,t,n):void 0},createChild:function(e,t,n){return r(n,t,e._mountIndex)},removeChild:function(e,t){return i(e,t)},_mountChildAtIndex:function(e,t,n,r,o){var i=d.mountComponent(e,r,this,this._nativeContainerInfo,o);return e._mountIndex=n,this.createChild(e,t,i)},_unmountChild:function(e,t){var n=this.removeChild(e,t);return e._mountIndex=null,n}}};t.exports=m},{128:128,160:160,168:168,31:31,36:36,39:39,75:75,80:80,89:89}],80:[function(e,t,n){"use strict";var r=e(171),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});t.exports=o},{171:171}],81:[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 c?void 0:u(!1),new c(e)}function i(e){return new d(e)}function a(e){return e instanceof d}var s=e(179),u=e(168),l=null,c=null,p={},d=null,f={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){s(p,e)}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:f};t.exports=h},{168:168,179:179}],82:[function(e,t,n){"use strict";var r=e(64),o=e(168),i={NATIVE:0,COMPOSITE:1,EMPTY:2,getType:function(e){return null===e||e===!1?i.EMPTY:r.isValidElement(e)?"function"==typeof e.type?i.COMPOSITE:i.NATIVE:void o(!1)}};t.exports=i},{168:168,64:64}],83:[function(e,t,n){"use strict";function r(e,t){}var o=(e(178),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")}});t.exports=o},{178:178}],84:[function(e,t,n){"use strict";var r=e(168),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){o.isValidOwner(n)?void 0:r(!1),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){o.isValidOwner(n)?void 0:r(!1);var i=n.getPublicInstance();i&&i.refs[t]===e.getPublicInstance()&&n.detachRef(t)}};t.exports=o},{168:168}],85:[function(e,t,n){"use strict";var r={};t.exports=r},{}],86:[function(e,t,n){"use strict";var r=e(171),o=r({prop:null,context:null,childContext:null});t.exports=o},{171:171}],87:[function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function o(e){function t(t,n,r,o,i,a){if(o=o||T,a=a||r,null==n[r]){var s=b[i];return t?new Error("Required "+s+" `"+a+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i,a)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function i(e){function t(t,n,r,o,i){var a=t[n],s=m(a);if(s!==e){var u=b[o],l=g(a);return new Error("Invalid "+u+" `"+i+"` of type "+("`"+l+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return o(t)}function a(){return o(_.thatReturns(null))}function s(e){function t(t,n,r,o,i){if("function"!=typeof e)return new Error("Property `"+i+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var a=t[n];if(!Array.isArray(a)){var s=b[o],u=m(a);return new Error("Invalid "+s+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var l=0;l<a.length;l++){var c=e(a,l,r,o,i+"["+l+"]");if(c instanceof Error)return c}return null}return o(t)}function u(){function e(e,t,n,r,o){if(!C.isValidElement(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return o(e)}function l(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=b[o],s=e.name||T,u=y(t[n]);return new Error("Invalid "+a+" `"+i+"` of type "+("`"+u+"` supplied to `"+r+"`, expected ")+("instance of `"+s+"`."))}return null}return o(t)}function c(e){function t(t,n,o,i,a){for(var s=t[n],u=0;u<e.length;u++)if(r(s,e[u]))return null;var l=b[i],c=JSON.stringify(e);return new Error("Invalid "+l+" `"+a+"` of value `"+s+"` "+("supplied to `"+o+"`, expected one of "+c+"."))}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function p(e){function t(t,n,r,o,i){if("function"!=typeof e)return new Error("Property `"+i+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var a=t[n],s=m(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type "+("`"+s+"` supplied to `"+r+"`, expected an object."))}for(var l in a)if(a.hasOwnProperty(l)){var c=e(a,l,r,o,i+"."+l);if(c instanceof Error)return c}return null}return o(t)}function d(e){function t(t,n,r,o,i){for(var a=0;a<e.length;a++){var s=e[a];if(null==s(t,n,r,o,i))return null}var u=b[o];return new Error("Invalid "+u+" `"+i+"` supplied to "+("`"+r+"`."))}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function f(){function e(e,t,n,r,o){if(!v(e[t])){var i=b[r];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return o(e)}function h(e){function t(t,n,r,o,i){var a=t[n],s=m(a);if("object"!==s){var u=b[o];return new Error("Invalid "+u+" `"+i+"` of type `"+s+"` "+("supplied to `"+r+"`, expected `object`."))}for(var l in e){var c=e[l];if(c){var p=c(a,l,r,o,i+"."+l);if(p)return p}}return null}return o(t)}function v(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(v);if(null===e||C.isValidElement(e))return!0;var t=E(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!v(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!v(o[1]))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 g(e){var t=m(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function y(e){return e.constructor&&e.constructor.name?e.constructor.name:T}var C=e(64),b=e(85),_=e(160),E=e(134),T="<<anonymous>>",x={array:i("array"),bool:i("boolean"),func:i("function"),number:i("number"),object:i("object"),string:i("string"),any:a(),arrayOf:s,element:u(),instanceOf:l,node:f(),objectOf:p,oneOf:c,oneOfType:d,shape:h};t.exports=x},{134:134,160:160,64:64,85:85}],88:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=i.getPooled(null),this.useCreateElement=e}var o=e(179),i=e(5),a=e(26),s=e(28),u=e(73),l=e(119),c={initialize:u.getSelectionInformation,close:u.restoreSelection},p={initialize:function(){var e=s.isEnabled();return s.setEnabled(!1),e},close:function(e){s.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},checkpoint:function(){return this.reactMountReady.checkpoint()},rollback:function(e){this.reactMountReady.rollback(e)},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};o(r.prototype,l.Mixin,h),a.addPoolingTo(r),t.exports=r},{119:119,179:179,26:26,28:28,5:5,73:73}],89:[function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=e(90),i=(e(75),e(168)),a={mountComponent:function(e,t,n,o,i){var a=e.mountComponent(t,n,o,i);return e._currentElement&&null!=e._currentElement.ref&&t.getReactMountReady().enqueue(r,e),a},getNativeNode:function(e){return e.getNativeNode()},unmountComponent:function(e,t){o.detachRefs(e,e._currentElement),e.unmountComponent(t)},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var s=o.shouldUpdateRefs(a,t);s&&o.detachRefs(e,a),e.receiveComponent(t,n,i),s&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t,n){return e._updateBatchNumber!==n?void(null!=e._updateBatchNumber&&e._updateBatchNumber!==n+1?i(!1):void 0):void e.performUpdateIfNecessary(t)}};t.exports=a},{168:168,75:75,90:90}],90:[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(84),a={};a.attachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null===e||e===!1,r=null===t||t===!1;return n||r||t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&o(n,e,t._owner)}},t.exports=a},{84:84}],91:[function(e,t,n){"use strict";var r={isBatchingUpdates:!1,batchedUpdates:function(e){}};t.exports=r},{}],92:[function(e,t,n){"use strict";function r(e,t){var n;try{return f.injection.injectBatchingStrategy(p),n=d.getPooled(t),n.perform(function(){var r=v(e),o=c.mountComponent(r,n,null,a(),h);return t||(o=l.addChecksumToMarkup(o)),o},null)}finally{d.release(n),f.injection.injectBatchingStrategy(s)}}function o(e){return u.isValidElement(e)?void 0:m(!1),r(e,!1)}function i(e){return u.isValidElement(e)?void 0:m(!1),r(e,!0)}var a=e(45),s=e(62),u=e(64),l=(e(75),e(77)),c=e(89),p=e(91),d=e(93),f=e(99),h=e(161),v=e(139),m=e(168);t.exports={renderToString:o,renderToStaticMarkup:i}},{139:139,161:161,168:168,45:45,62:62,64:64,75:75,77:77,89:89,91:91,93:93,99:99}],93:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.useCreateElement=!1}var o=e(179),i=e(26),a=e(119),s=[],u={enqueue:function(){}},l={getTransactionWrappers:function(){return s},getReactMountReady:function(){return u},destructor:function(){},checkpoint:function(){},rollback:function(){}};o(r.prototype,a.Mixin,l),i.addPoolingTo(r),t.exports=r},{119:119,179:179,26:26}],94:[function(e,t,n){"use strict";function r(e,t){var n={};return function(r){n[t]=r,e.setState(n)}}var o={createStateSetter:function(e,t){return function(n,r,o,i,a,s){var u=t.call(e,n,r,o,i,a,s);u&&e.setState(u)}},createStateKeySetter:function(e,t){var n=e.__keySetters||(e.__keySetters={});return n[t]||(n[t]=r(e,t))}};o.Mixin={createStateSetter:function(e){return o.createStateSetter(this,e)},createStateKeySetter:function(e){return o.createStateKeySetter(this,e)}},t.exports=o},{}],95:[function(e,t,n){"use strict";var r=e(128),o={getChildMapping:function(e){return e?r(e):e},mergeChildMappings:function(e,t){function n(n){return t.hasOwnProperty(n)?t[n]:e[n]}e=e||{},t=t||{};var r={},o=[];for(var i in e)t.hasOwnProperty(i)?o.length&&(r[i]=o,o=[]):o.push(i);var a,s={};for(var u in t){if(r.hasOwnProperty(u))for(a=0;a<r[u].length;a++){var l=r[u][a];s[r[u][a]]=n(l)}s[u]=n(u)}for(a=0;a<o.length;a++)s[o[a]]=n(o[a]);return s}};t.exports=o},{128:128}],96:[function(e,t,n){"use strict";function r(){var e=s("animationend"),t=s("transitionend");e&&u.push(e),t&&u.push(t)}function o(e,t,n){e.addEventListener(t,n,!1)}function i(e,t,n){e.removeEventListener(t,n,!1)}var a=e(154),s=e(138),u=[];a.canUseDOM&&r();var l={addEndEventListener:function(e,t){return 0===u.length?void window.setTimeout(t,0):void u.forEach(function(n){o(e,n,t)})},removeEndEventListener:function(e,t){0!==u.length&&u.forEach(function(n){i(e,n,t)})}};t.exports=l},{138:138,154:154}],97:[function(e,t,n){"use strict";var r=e(179),o=e(27),i=e(95),a=e(160),s=o.createClass({displayName:"ReactTransitionGroup",propTypes:{component:o.PropTypes.any,childFactory:o.PropTypes.func},getDefaultProps:function(){return{component:"span",childFactory:a.thatReturnsArgument}},getInitialState:function(){return{children:i.getChildMapping(this.props.children)}},componentWillMount:function(){this.currentlyTransitioningKeys={},this.keysToEnter=[],this.keysToLeave=[]},componentDidMount:function(){var e=this.state.children;for(var t in e)e[t]&&this.performAppear(t)},componentWillReceiveProps:function(e){var t=i.getChildMapping(e.children),n=this.state.children;this.setState({children:i.mergeChildMappings(n,t)});var r;for(r in t){var o=n&&n.hasOwnProperty(r);!t[r]||o||this.currentlyTransitioningKeys[r]||this.keysToEnter.push(r)}for(r in n){var a=t&&t.hasOwnProperty(r);!n[r]||a||this.currentlyTransitioningKeys[r]||this.keysToLeave.push(r)}},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performAppear:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillAppear?t.componentWillAppear(this._handleDoneAppearing.bind(this,e)):this._handleDoneAppearing(e)},_handleDoneAppearing:function(e){var t=this.refs[e];t.componentDidAppear&&t.componentDidAppear(),delete this.currentlyTransitioningKeys[e];var n=i.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performEnter:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillEnter?t.componentWillEnter(this._handleDoneEntering.bind(this,e)):this._handleDoneEntering(e)},_handleDoneEntering:function(e){var t=this.refs[e];t.componentDidEnter&&t.componentDidEnter(),delete this.currentlyTransitioningKeys[e];var n=i.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)||this.performLeave(e)},performLeave:function(e){this.currentlyTransitioningKeys[e]=!0;var t=this.refs[e];t.componentWillLeave?t.componentWillLeave(this._handleDoneLeaving.bind(this,e)):this._handleDoneLeaving(e)},_handleDoneLeaving:function(e){var t=this.refs[e];t.componentDidLeave&&t.componentDidLeave(),delete this.currentlyTransitioningKeys[e];var n=i.getChildMapping(this.props.children);n&&n.hasOwnProperty(e)?this.performEnter(e):this.setState(function(t){var n=r({},t.children);return delete n[e],{children:n}})},render:function(){var e=[];for(var t in this.state.children){var n=this.state.children[t];n&&e.push(o.cloneElement(this.props.childFactory(n),{ref:t,key:t}))}return o.createElement(this.props.component,this.props,e)}});t.exports=s},{160:160,179:179,27:27,95:95}],98:[function(e,t,n){"use strict";function r(e){a.enqueueUpdate(e)}function o(e,t){var n=i.get(e);return n?n:null}var i=(e(39),e(74)),a=e(99),s=e(168),u=(e(178),{isMounted:function(e){var t=i.get(e);return t?!!t._renderedComponent:!1},enqueueCallback:function(e,t,n){u.validateCallback(t,n);var i=o(e);return i?(i._pendingCallbacks?i._pendingCallbacks.push(t):i._pendingCallbacks=[t],void r(i)):null},enqueueCallbackInternal:function(e,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)}},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e?s(!1):void 0}});t.exports=u},{168:168,178:178,39:39,74:74,99:99}],99:[function(e,t,n){"use strict";function r(){w.ReactReconcileTransaction&&_?void 0:m(!1)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=p.getPooled(),this.reconcileTransaction=w.ReactReconcileTransaction.getPooled(!0)}function i(e,t,n,o,i,a){r(),_.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;t!==g.length?m(!1):void 0,g.sort(a),y++;for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;r._pendingCallbacks=null;var i;if(f.logTopLevelRenders){var s=r;r._currentElement.props===r._renderedComponent._currentElement&&(s=r._renderedComponent),i="React update: "+s.getName(),console.time(i)}if(h.performUpdateIfNecessary(r,e.reconcileTransaction,y),i&&console.timeEnd(i),o)for(var u=0;u<o.length;u++)e.callbackQueue.enqueue(o[u],r.getPublicInstance())}}function u(e){return r(),_.isBatchingUpdates?(g.push(e),void(null==e._updateBatchNumber&&(e._updateBatchNumber=y+1))):void _.batchedUpdates(u,e)}function l(e,t){_.isBatchingUpdates?void 0:m(!1),C.enqueue(e,t),b=!0}var c=e(179),p=e(5),d=e(26),f=e(70),h=(e(75),e(89)),v=e(119),m=e(168),g=[],y=0,C=p.getPooled(),b=!1,_=null,E={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),N()):g.length=0}},T={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},x=[E,T];c(o.prototype,v.Mixin,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null,p.release(this.callbackQueue),this.callbackQueue=null,w.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return v.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),d.addPoolingTo(o);var N=function(){for(;g.length||b;){if(g.length){var e=o.getPooled();e.perform(s,null,e),o.release(e)}if(b){b=!1;var t=C;C=p.getPooled(),t.notifyAll(),p.release(t)}}},P={injectReconcileTransaction:function(e){e?void 0:m(!1),w.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:m(!1),"function"!=typeof e.batchedUpdates?m(!1):void 0,"boolean"!=typeof e.isBatchingUpdates?m(!1):void 0,_=e}},w={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:u,flushBatchedUpdates:N,injection:P,asap:l};t.exports=w},{119:119,168:168,179:179,26:26,5:5,70:70,75:75,89:89}],100:[function(e,t,n){"use strict";t.exports="15.1.0"},{}],101:[function(e,t,n){"use strict";var r=e(24),o=e(27),i=e(37),a=e(29),s=e(71),u=e(97),l=e(147),c=e(150);o.addons={CSSTransitionGroup:a,LinkedStateMixin:r,PureRenderMixin:i,TransitionGroup:u,createFragment:s.create,shallowCompare:l,update:c},t.exports=o},{147:147,150:150,24:24,27:27,29:29,37:37,71:71,97:97}],102:[function(e,t,n){"use strict";var r=e(179),o=e(40),i=e(56),a=e(101),s=r({__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:o,__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:i},a);t.exports=s},{101:101,179:179,40:40,56:56}],103:[function(e,t,n){"use strict";var r={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},o={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering","in":0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",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",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},i={Properties:{},DOMAttributeNamespaces:{xlinkActuate:r.xlink,xlinkArcrole:r.xlink,xlinkHref:r.xlink,xlinkRole:r.xlink,xlinkShow:r.xlink,xlinkTitle:r.xlink,xlinkType:r.xlink,xmlBase:r.xml,xmlLang:r.xml,xmlSpace:r.xml},DOMAttributeNames:{}};Object.keys(o).forEach(function(e){i.Properties[e]=0,o[e]&&(i.DOMAttributeNames[e]=o[e])}),t.exports=i},{}],104:[function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&l.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(_||null==y||y!==p())return null;var n=r(y);if(!b||!h(b,n)){b=n;var o=c.getPooled(g.select,C,e,t);return o.type="select",o.target=y,a.accumulateTwoPhaseDispatches(o),o}return null}var i=e(16),a=e(20),s=e(154),u=e(44),l=e(73),c=e(110),p=e(163),d=e(141),f=e(172),h=e(177),v=i.topLevelTypes,m=s.canUseDOM&&"documentMode"in document&&document.documentMode<=11,g={select:{phasedRegistrationNames:{bubbled:f({onSelect:null}),captured:f({onSelectCapture:null})},dependencies:[v.topBlur,v.topContextMenu,v.topFocus,v.topKeyDown,v.topMouseDown,v.topMouseUp,v.topSelectionChange]}},y=null,C=null,b=null,_=!1,E=!1,T=f({onSelect:null}),x={eventTypes:g,extractEvents:function(e,t,n,r){if(!E)return null;var i=t?u.getNodeFromInstance(t):window;switch(e){case v.topFocus:(d(i)||"true"===i.contentEditable)&&(y=i,C=t,b=null);break;case v.topBlur:y=null,C=null,b=null;break;case v.topMouseDown:_=!0;break;case v.topContextMenu:case v.topMouseUp:return _=!1,o(n,r);case v.topSelectionChange:if(m)break;case v.topKeyDown:case v.topKeyUp:return o(n,r)}return null},didPutListener:function(e,t,n){t===T&&(E=!0)}};t.exports=x},{110:110,141:141,154:154,16:16,163:163,172:172,177:177,20:20,44:44,73:73}],105:[function(e,t,n){"use strict";var r=e(16),o=e(153),i=e(20),a=e(44),s=e(106),u=e(107),l=e(110),c=e(111),p=e(113),d=e(114),f=e(109),h=e(115),v=e(116),m=e(117),g=e(118),y=e(160),C=e(130),b=e(168),_=e(172),E=r.topLevelTypes,T={abort:{phasedRegistrationNames:{bubbled:_({onAbort:!0}),captured:_({onAbortCapture:!0})}},animationEnd:{phasedRegistrationNames:{bubbled:_({onAnimationEnd:!0}),captured:_({onAnimationEndCapture:!0})}},animationIteration:{phasedRegistrationNames:{bubbled:_({onAnimationIteration:!0}),captured:_({onAnimationIterationCapture:!0})}},animationStart:{phasedRegistrationNames:{bubbled:_({onAnimationStart:!0}),captured:_({onAnimationStartCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:_({onBlur:!0}),captured:_({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:_({onCanPlay:!0}),captured:_({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:_({onCanPlayThrough:!0}),captured:_({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:_({onClick:!0}),captured:_({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:_({onContextMenu:!0}),captured:_({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:_({onCopy:!0}),captured:_({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:_({onCut:!0}),captured:_({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:_({onDoubleClick:!0}),captured:_({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:_({onDrag:!0}),captured:_({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:_({onDragEnd:!0}),captured:_({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:_({onDragEnter:!0}),captured:_({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:_({onDragExit:!0}),captured:_({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:_({onDragLeave:!0}),captured:_({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:_({onDragOver:!0}),captured:_({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:_({onDragStart:!0}),captured:_({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:_({onDrop:!0}),captured:_({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:_({onDurationChange:!0}),captured:_({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:_({onEmptied:!0}),captured:_({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:_({onEncrypted:!0}),captured:_({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:_({onEnded:!0}),captured:_({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:_({onError:!0}),captured:_({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:_({onFocus:!0}),captured:_({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:_({onInput:!0}),captured:_({onInputCapture:!0})}},invalid:{phasedRegistrationNames:{bubbled:_({onInvalid:!0}),captured:_({onInvalidCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:_({onKeyDown:!0}),captured:_({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:_({onKeyPress:!0}),captured:_({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:_({onKeyUp:!0}),captured:_({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:_({onLoad:!0}),captured:_({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:_({onLoadedData:!0}),captured:_({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:_({onLoadedMetadata:!0}),captured:_({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:_({onLoadStart:!0}),captured:_({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:_({onMouseDown:!0}),captured:_({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:_({onMouseMove:!0}),captured:_({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:_({onMouseOut:!0}),captured:_({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:_({onMouseOver:!0}),captured:_({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:_({onMouseUp:!0}),captured:_({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:_({onPaste:!0}),captured:_({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:_({onPause:!0}),captured:_({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:_({onPlay:!0}),captured:_({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:_({onPlaying:!0}),captured:_({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:_({onProgress:!0}),captured:_({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:_({onRateChange:!0}),captured:_({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:_({onReset:!0}),captured:_({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:_({onScroll:!0}),captured:_({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:_({onSeeked:!0}),captured:_({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:_({onSeeking:!0}),captured:_({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:_({onStalled:!0}),captured:_({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:_({onSubmit:!0}),captured:_({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:_({onSuspend:!0}),captured:_({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:_({onTimeUpdate:!0}),captured:_({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:_({onTouchCancel:!0}),captured:_({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:_({
onTouchEnd:!0}),captured:_({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:_({onTouchMove:!0}),captured:_({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:_({onTouchStart:!0}),captured:_({onTouchStartCapture:!0})}},transitionEnd:{phasedRegistrationNames:{bubbled:_({onTransitionEnd:!0}),captured:_({onTransitionEndCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:_({onVolumeChange:!0}),captured:_({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:_({onWaiting:!0}),captured:_({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:_({onWheel:!0}),captured:_({onWheelCapture:!0})}}},x={topAbort:T.abort,topAnimationEnd:T.animationEnd,topAnimationIteration:T.animationIteration,topAnimationStart:T.animationStart,topBlur:T.blur,topCanPlay:T.canPlay,topCanPlayThrough:T.canPlayThrough,topClick:T.click,topContextMenu:T.contextMenu,topCopy:T.copy,topCut:T.cut,topDoubleClick:T.doubleClick,topDrag:T.drag,topDragEnd:T.dragEnd,topDragEnter:T.dragEnter,topDragExit:T.dragExit,topDragLeave:T.dragLeave,topDragOver:T.dragOver,topDragStart:T.dragStart,topDrop:T.drop,topDurationChange:T.durationChange,topEmptied:T.emptied,topEncrypted:T.encrypted,topEnded:T.ended,topError:T.error,topFocus:T.focus,topInput:T.input,topInvalid:T.invalid,topKeyDown:T.keyDown,topKeyPress:T.keyPress,topKeyUp:T.keyUp,topLoad:T.load,topLoadedData:T.loadedData,topLoadedMetadata:T.loadedMetadata,topLoadStart:T.loadStart,topMouseDown:T.mouseDown,topMouseMove:T.mouseMove,topMouseOut:T.mouseOut,topMouseOver:T.mouseOver,topMouseUp:T.mouseUp,topPaste:T.paste,topPause:T.pause,topPlay:T.play,topPlaying:T.playing,topProgress:T.progress,topRateChange:T.rateChange,topReset:T.reset,topScroll:T.scroll,topSeeked:T.seeked,topSeeking:T.seeking,topStalled:T.stalled,topSubmit:T.submit,topSuspend:T.suspend,topTimeUpdate:T.timeUpdate,topTouchCancel:T.touchCancel,topTouchEnd:T.touchEnd,topTouchMove:T.touchMove,topTouchStart:T.touchStart,topTransitionEnd:T.transitionEnd,topVolumeChange:T.volumeChange,topWaiting:T.waiting,topWheel:T.wheel};for(var N in x)x[N].dependencies=[N];var P=_({onClick:null}),w={},S={eventTypes:T,extractEvents:function(e,t,n,r){var o=x[e];if(!o)return null;var a;switch(e){case E.topAbort:case E.topCanPlay:case E.topCanPlayThrough:case E.topDurationChange:case E.topEmptied:case E.topEncrypted:case E.topEnded:case E.topError:case E.topInput:case E.topInvalid:case E.topLoad:case E.topLoadedData:case E.topLoadedMetadata:case E.topLoadStart:case E.topPause:case E.topPlay:case E.topPlaying:case E.topProgress:case E.topRateChange:case E.topReset:case E.topSeeked:case E.topSeeking:case E.topStalled:case E.topSubmit:case E.topSuspend:case E.topTimeUpdate:case E.topVolumeChange:case E.topWaiting:a=l;break;case E.topKeyPress:if(0===C(n))return null;case E.topKeyDown:case E.topKeyUp:a=p;break;case E.topBlur:case E.topFocus:a=c;break;case E.topClick:if(2===n.button)return null;case E.topContextMenu:case E.topDoubleClick:case E.topMouseDown:case E.topMouseMove:case E.topMouseOut:case E.topMouseOver:case E.topMouseUp:a=d;break;case E.topDrag:case E.topDragEnd:case E.topDragEnter:case E.topDragExit:case E.topDragLeave:case E.topDragOver:case E.topDragStart:case E.topDrop:a=f;break;case E.topTouchCancel:case E.topTouchEnd:case E.topTouchMove:case E.topTouchStart:a=h;break;case E.topAnimationEnd:case E.topAnimationIteration:case E.topAnimationStart:a=s;break;case E.topTransitionEnd:a=v;break;case E.topScroll:a=m;break;case E.topWheel:a=g;break;case E.topCopy:case E.topCut:case E.topPaste:a=u}a?void 0:b(!1);var y=a.getPooled(o,t,n,r);return i.accumulateTwoPhaseDispatches(y),y},didPutListener:function(e,t,n){if(t===P){var r=e._rootNodeID,i=a.getNodeFromInstance(e);w[r]||(w[r]=o.listen(i,"click",y))}},willDeleteListener:function(e,t){if(t===P){var n=e._rootNodeID;w[n].remove(),delete w[n]}}};t.exports=S},{106:106,107:107,109:109,110:110,111:111,113:113,114:114,115:115,116:116,117:117,118:118,130:130,153:153,16:16,160:160,168:168,172:172,20:20,44:44}],106:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(110),i={animationName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),t.exports=r},{110:110}],107:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(110),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),t.exports=r},{110:110}],108:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(110),i={data:null};o.augmentClass(r,i),t.exports=r},{110:110}],109:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(114),i={dataTransfer:null};o.augmentClass(r,i),t.exports=r},{114:114}],110:[function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var s=o[i];s?this[i]=s(n):"target"===i?this.target=r:this[i]=n[i]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;return u?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse,this}var o=e(179),i=e(26),a=e(160),s=(e(178),"function"==typeof Proxy,["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"]),u={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;for(var n=0;n<s.length;n++)this[s[n]]=null}}),r.Interface=u,r.augmentClass=function(e,t){var n=this,r=function(){};r.prototype=n.prototype;var a=new r;o(a,e.prototype),e.prototype=a,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,i.addPoolingTo(e,i.fourArgumentPooler)},i.addPoolingTo(r,i.fourArgumentPooler),t.exports=r},{160:160,178:178,179:179,26:26}],111:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(117),i={relatedTarget:null};o.augmentClass(r,i),t.exports=r},{117:117}],112:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(110),i={data:null};o.augmentClass(r,i),t.exports=r},{110:110}],113:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(117),i=e(130),a=e(131),s=e(132),u={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,u),t.exports=r},{117:117,130:130,131:131,132:132}],114:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(117),i=e(120),a=e(132),s={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,s),t.exports=r},{117:117,120:120,132:132}],115:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(117),i=e(132),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),t.exports=r},{117:117,132:132}],116:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(110),i={propertyName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),t.exports=r},{110:110}],117:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(110),i=e(133),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},{110:110,133:133}],118:[function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=e(114),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},{114:114}],119:[function(e,t,n){"use strict";var r=e(168),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,s,u){this.isInTransaction()?r(!1):void 0;var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=e.call(t,n,o,i,a,s,u),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=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){this.isInTransaction()?void 0:r(!1);for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],s=this.wrapperInitData[n];try{o=!0,s!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,s),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(u){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};t.exports=i},{168:168}],120:[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},{}],121:[function(e,t,n){"use strict";function r(e,t){if(null==t?o(!1):void 0,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(168);t.exports=r},{168:168}],122:[function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0,i=e.length,a=-4&i;a>r;){for(var s=Math.min(r+4096,a);s>r;r+=4)n+=(t+=e.charCodeAt(r))+(t+=e.charCodeAt(r+1))+(t+=e.charCodeAt(r+2))+(t+=e.charCodeAt(r+3));t%=o,n%=o}for(;i>r;r++)n+=t+=e.charCodeAt(r);return t%=o,n%=o,t|n<<16}var o=65521;t.exports=r},{}],123:[function(e,t,n){"use strict";var r=!1;t.exports=r},{}],124:[function(e,t,n){"use strict";var r=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,o)})}:e};t.exports=r},{}],125:[function(e,t,n){"use strict";function r(e,t,n){var r=null==t||"boolean"==typeof t||""===t;if(r)return"";var o=isNaN(t);return o||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=e(3),i=(e(178),o.isUnitlessNumber);t.exports=r},{178:178,3:3}],126:[function(e,t,n){"use strict";function r(e){return i[e]}function o(e){return(""+e).replace(a,r)}var i={"&":"&",">":">","<":"<",'"':""","'":"'"},a=/[&><"']/g;t.exports=o},{}],127:[function(e,t,n){"use strict";function r(e){if(null==e)return null;if(1===e.nodeType)return e;var t=i.get(e);return t?(t=a(t),t?o.getNodeFromInstance(t):null):void s(("function"==typeof e.render,!1))}var o=(e(39),e(44)),i=e(74),a=e(135),s=e(168);e(178);t.exports=r},{135:135,168:168,178:178,39:39,44:44,74:74}],128:[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(23),e(149));e(178);t.exports=o},{149:149,178:178,23:23}],129:[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},{}],130:[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},{}],131:[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(130),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},{130:130}],132:[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},{}],133:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),3===t.nodeType?t.parentNode:t}t.exports=r},{}],134:[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},{}],135:[function(e,t,n){"use strict";function r(e){for(var t;(t=e._renderedNodeType)===o.COMPOSITE;)e=e._renderedComponent;return t===o.NATIVE?e._renderedComponent:t===o.EMPTY?null:void 0}var o=e(82);t.exports=r},{82:82}],136:[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},{}],137:[function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=e(154),i=null;t.exports=r},{154:154}],138:[function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(s[e])return s[e];if(!a[e])return e;var t=a[e];for(var n in t)if(t.hasOwnProperty(n)&&n in u)return s[e]=t[n];return""}var i=e(154),a={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},s={},u={};i.canUseDOM&&(u=document.createElement("div").style,"AnimationEvent"in window||(delete a.animationend.animation,delete a.animationiteration.animation,delete a.animationstart.animation),"TransitionEvent"in window||delete a.transitionend.transition),t.exports=o},{154:154}],139:[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){var t,n=null===e||e===!1;if(n)t=s.create(o);else if("object"==typeof e){var i=e;!i||"function"!=typeof i.type&&"string"!=typeof i.type?l(!1):void 0,t="string"==typeof i.type?u.createInternalComponent(i):r(i.type)?new i.type(i):new c(i)}else"string"==typeof e||"number"==typeof e?t=u.createInstanceForText(e):l(!1);return t._mountIndex=0,t._mountImage=null,t}var i=e(179),a=e(38),s=e(66),u=e(81),l=(e(75),e(168)),c=(e(178),function(e){this.construct(e)});i(c.prototype,a.Mixin,{_instantiateReactComponent:o});t.exports=o},{168:168,178:178,179:179,38:38,66:66,75:75,81:81}],140:[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(154);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{154:154}],141:[function(e,t,n){"use strict";function r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&o[e.type]||"textarea"===t)}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=r},{}],142:[function(e,t,n){"use strict";function r(e){return o.isValidElement(e)?void 0:i(!1),e}var o=e(64),i=e(168);t.exports=r},{168:168,64:64}],143:[function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=e(126);t.exports=r},{126:126}],144:[function(e,t,n){"use strict";var r=e(78);t.exports=r.renderSubtreeIntoContainer},{78:78}],145:[function(e,t,n){"use strict";var r=e(154),o=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=e(124),s=a(function(e,t){e.innerHTML=t});if(r.canUseDOM){var u=document.createElement("div");u.innerHTML=" ",""===u.innerHTML&&(s=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}),u=null}t.exports=s},{124:124,154:154}],146:[function(e,t,n){"use strict";var r=e(154),o=e(126),i=e(145),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),t.exports=a},{126:126,145:145,154:154}],147:[function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=e(177);t.exports=r},{177:177}],148:[function(e,t,n){"use strict";function r(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}t.exports=r},{}],149:[function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?l.escape(e.key):t.toString(36)}function o(e,t,n,i){var d=typeof e;if("undefined"!==d&&"boolean"!==d||(e=null),null===e||"string"===d||"number"===d||a.isValidElement(e))return n(i,e,""===t?c+r(e,0):t),1;var f,h,v=0,m=""===t?c:t+p;if(Array.isArray(e))for(var g=0;g<e.length;g++)f=e[g],h=m+r(f,g),v+=o(f,h,n,i);else{var y=s(e);if(y){var C,b=y.call(e);if(y!==e.entries)for(var _=0;!(C=b.next()).done;)f=C.value,h=m+r(f,_++),v+=o(f,h,n,i);else for(;!(C=b.next()).done;){var E=C.value;E&&(f=E[1],h=m+l.escape(E[0])+p+r(f,0),v+=o(f,h,n,i))}}else"object"===d&&(String(e),u(!1))}return v}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=(e(39),e(64)),s=e(134),u=e(168),l=e(23),c=(e(178),"."),p=":";t.exports=i},{134:134,168:168,178:178,23:23,39:39,64:64}],150:[function(e,t,n){"use strict";function r(e){return Array.isArray(e)?e.concat():e&&"object"==typeof e?a(new e.constructor,e):e}function o(e,t,n){Array.isArray(e)?void 0:u(!1);var r=t[n];Array.isArray(r)?void 0:u(!1)}function i(e,t){if("object"!=typeof t?u(!1):void 0,l.call(t,f))return 1!==Object.keys(t).length?u(!1):void 0,t[f];var n=r(e);if(l.call(t,h)){var s=t[h];s&&"object"==typeof s?void 0:u(!1),n&&"object"==typeof n?void 0:u(!1),a(n,t[h])}l.call(t,c)&&(o(e,t,c),t[c].forEach(function(e){n.push(e)})),l.call(t,p)&&(o(e,t,p),t[p].forEach(function(e){n.unshift(e)})),l.call(t,d)&&(Array.isArray(e)?void 0:u(!1),Array.isArray(t[d])?void 0:u(!1),t[d].forEach(function(e){Array.isArray(e)?void 0:u(!1),n.splice.apply(n,e)})),l.call(t,v)&&("function"!=typeof t[v]?u(!1):void 0,n=t[v](n));for(var m in t)g.hasOwnProperty(m)&&g[m]||(n[m]=i(e[m],t[m]));return n}var a=e(179),s=e(172),u=e(168),l={}.hasOwnProperty,c=s({$push:null}),p=s({$unshift:null}),d=s({$splice:null}),f=s({$set:null}),h=s({$merge:null}),v=s({$apply:null}),m=[c,p,d,f,h,v],g={};m.forEach(function(e){g[e]=!0}),t.exports=i},{168:168,172:172,179:179}],151:[function(e,t,n){"use strict";var r=(e(179),e(160)),o=(e(178),r);t.exports=o},{160:160,178:178,179:179}],152:[function(e,t,n){"use strict";function r(e,t){for(var n=e;n.parentNode;)n=n.parentNode;var r=n.querySelectorAll(t);return-1!==Array.prototype.indexOf.call(r,e)}var o=e(168),i={addClass:function(e,t){return/\s/.test(t)?o(!1):void 0,t&&(e.classList?e.classList.add(t):i.hasClass(e,t)||(e.className=e.className+" "+t)),e},removeClass:function(e,t){return/\s/.test(t)?o(!1):void 0,t&&(e.classList?e.classList.remove(t):i.hasClass(e,t)&&(e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),e},conditionClass:function(e,t,n){return(n?i.addClass:i.removeClass)(e,t)},hasClass:function(e,t){return/\s/.test(t)?o(!1):void 0,e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")>-1},matchesSelector:function(e,t){var n=e.matches||e.webkitMatchesSelector||e.mozMatchesSelector||e.msMatchesSelector||function(t){return r(e,t)};return n.call(e,t)}};t.exports=i},{168:168}],153:[function(e,t,n){"use strict";var r=e(160),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},{160:160}],154:[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},{}],155:[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},{}],156:[function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=e(155),i=/^-ms-/;t.exports=r},{155:155}],157:[function(e,t,n){"use strict";function r(e,t){return e&&t?e===t?!0:o(e)?!1:o(t)?r(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var o=e(170);t.exports=r},{170:170}],158:[function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?a(!1):void 0,"number"!=typeof t?a(!1):void 0,0===t||t-1 in e?void 0:a(!1),"function"==typeof e.callee?a(!1):void 0,e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),o=0;t>o;o++)r[o]=e[o];return r}function o(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function i(e){return o(e)?Array.isArray(e)?e.slice():r(e):[e]}var a=e(168);t.exports=i},{168:168}],159:[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;l?void 0:u(!1);var o=r(e),i=o&&s(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&&(t?void 0:u(!1),a(p).forEach(t));for(var d=Array.from(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return d}var i=e(154),a=e(158),s=e(164),u=e(168),l=i.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=o},{154:154,158:158,164:164,168:168}],160:[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},{}],161:[function(e,t,n){"use strict";var r={};t.exports=r},{}],162:[function(e,t,n){"use strict";function r(e){try{e.focus()}catch(t){}}t.exports=r},{}],163:[function(e,t,n){"use strict";function r(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=r},{}],164:[function(e,t,n){"use strict";function r(e){return a?void 0:i(!1),d.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?d[e]:null}var o=e(154),i=e(168),a=o.canUseDOM?document.createElement("div"):null,s={},u=[1,'<select multiple="true">',"</select>"],l=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,'<svg xmlns="http://www.w3.org/2000/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:u,option:u,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c},f=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];f.forEach(function(e){d[e]=p,s[e]=!0}),t.exports=r},{154:154,168:168}],165:[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},{}],166:[function(e,t,n){"use strict";function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;t.exports=r},{}],167:[function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=e(166),i=/^ms-/;t.exports=r},{166:166}],168:[function(e,t,n){"use strict";function r(e,t,n,r,o,i,a,s){if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,s],c=0;u=new Error(t.replace(/%s/g,function(){return l[c++]})),u.name="Invariant Violation"}throw u.framesToPop=1,u}}t.exports=r},{}],169:[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},{}],170:[function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=e(169);t.exports=r},{169:169}],171:[function(e,t,n){"use strict";var r=e(168),o=function(e){var t,n={};e instanceof Object&&!Array.isArray(e)?void 0:r(!1);for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};t.exports=o},{168:168}],172:[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},{}],173:[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},{}],174:[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},{}],175:[function(e,t,n){"use strict";var r,o=e(154);o.canUseDOM&&(r=window.performance||window.msPerformance||window.webkitPerformance),t.exports=r||{}},{154:154}],176:[function(e,t,n){"use strict";var r,o=e(175);r=o.now?function(){return o.now()}:function(){return Date.now()},t.exports=r},{175:175}],177:[function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function o(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=0;a<n.length;a++)if(!i.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}var i=Object.prototype.hasOwnProperty;t.exports=o},{}],178:[function(e,t,n){"use strict";var r=e(160),o=r;t.exports=o},{160:160}],179:[function(e,t,n){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function o(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;10>n;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(i){return!1}}var i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;t.exports=o()?Object.assign:function(e,t){for(var n,o,s=r(e),u=1;u<arguments.length;u++){n=Object(arguments[u]);for(var l in n)i.call(n,l)&&(s[l]=n[l]);if(Object.getOwnPropertySymbols){o=Object.getOwnPropertySymbols(n);for(var c=0;c<o.length;c++)a.call(n,o[c])&&(s[o[c]]=n[o[c]])}}return s}},{}]},{},[102])(102)}); |
ajax/libs/react-router-bootstrap/0.21.0/ReactRouterBootstrap.js | holtkamp/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["ReactRouterBootstrap"] = factory(require("react"));
else
root["ReactRouterBootstrap"] = 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 _IndexLinkContainer2 = __webpack_require__(1);
var _IndexLinkContainer3 = _interopRequireDefault(_IndexLinkContainer2);
exports.IndexLinkContainer = _IndexLinkContainer3['default'];
var _LinkContainer2 = __webpack_require__(3);
var _LinkContainer3 = _interopRequireDefault(_LinkContainer2);
exports.LinkContainer = _LinkContainer3['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; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _LinkContainer = __webpack_require__(3);
var _LinkContainer2 = _interopRequireDefault(_LinkContainer);
var IndexLinkContainer = (function (_React$Component) {
_inherits(IndexLinkContainer, _React$Component);
function IndexLinkContainer() {
_classCallCheck(this, IndexLinkContainer);
_get(Object.getPrototypeOf(IndexLinkContainer.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(IndexLinkContainer, [{
key: 'render',
value: function render() {
return _react2['default'].createElement(_LinkContainer2['default'], _extends({}, this.props, { onlyActiveOnIndex: true }));
}
}]);
return IndexLinkContainer;
})(_react2['default'].Component);
exports['default'] = IndexLinkContainer;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
// This is largely taken from rrtr/lib/Link.
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _rrtrLibLink = __webpack_require__(4);
var _rrtrLibLink2 = _interopRequireDefault(_rrtrLibLink);
var LinkContainer = (function (_React$Component) {
_inherits(LinkContainer, _React$Component);
function LinkContainer(props, context) {
_classCallCheck(this, LinkContainer);
_get(Object.getPrototypeOf(LinkContainer.prototype), 'constructor', this).call(this, props, context);
this.onClick = this.onClick.bind(this);
}
_createClass(LinkContainer, [{
key: 'onClick',
value: function onClick(event) {
if (this.props.disabled) {
event.preventDefault();
return;
}
if (this.props.children.props.onClick) {
this.props.children.props.onClick(event);
}
_rrtrLibLink2['default'].prototype.handleClick.call(this, event);
}
}, {
key: 'render',
value: function render() {
var router = this.context.router;
var _props = this.props;
var onlyActiveOnIndex = _props.onlyActiveOnIndex;
var to = _props.to;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['onlyActiveOnIndex', 'to', 'children']);
props.onClick = this.onClick;
// Ignore if rendered outside Router context; simplifies unit testing.
if (router) {
props.href = router.createHref(to);
if (props.active == null) {
props.active = router.isActive(to, onlyActiveOnIndex);
}
}
return _react2['default'].cloneElement(_react2['default'].Children.only(children), props);
}
}]);
return LinkContainer;
})(_react2['default'].Component);
exports['default'] = LinkContainer;
LinkContainer.propTypes = {
onlyActiveOnIndex: _react2['default'].PropTypes.bool.isRequired,
to: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.object]).isRequired,
onClick: _react2['default'].PropTypes.func,
active: _react2['default'].PropTypes.bool,
disabled: _react2['default'].PropTypes.bool.isRequired,
children: _react2['default'].PropTypes.node.isRequired
};
LinkContainer.contextTypes = {
router: _react2['default'].PropTypes.object
};
LinkContainer.defaultProps = {
onlyActiveOnIndex: false,
disabled: false
};
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _routerWarning = __webpack_require__(5);
var _routerWarning2 = _interopRequireDefault(_routerWarning);
var _React$PropTypes = _react2['default'].PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = _react2['default'].createClass({
displayName: 'Link',
contextTypes: {
router: object
},
propTypes: {
to: oneOfType([string, object]).isRequired,
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
className: '',
style: {}
};
},
handleClick: function handleClick(event) {
var allowTransition = true;
if (this.props.onClick) this.props.onClick(event);
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
if (event.defaultPrevented === true) allowTransition = false;
// If target prop is set (e.g. to "_blank") let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) {
if (!allowTransition) event.preventDefault();
return;
}
event.preventDefault();
if (allowTransition) {
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var _location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(_location);
}
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
true ? _routerWarning2['default'](!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : undefined;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
var _location2 = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(_location2);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(_location2, onlyActiveOnIndex)) {
if (activeClassName) props.className += props.className === '' ? activeClassName : ' ' + activeClassName;
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return _react2['default'].createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
exports['default'] = Link;
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = routerWarning;
exports._resetWarned = _resetWarned;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _warning = __webpack_require__(6);
var _warning2 = _interopRequireDefault(_warning);
var warned = {};
function routerWarning(falseToWarn, message) {
// Only issue deprecation warnings once.
if (message.indexOf('deprecated') !== -1) {
if (warned[message]) {
return;
}
warned[message] = true;
}
message = '[react-router] ' + message;
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
true ? _warning2['default'].apply(undefined, [falseToWarn, message].concat(args)) : undefined;
}
function _resetWarned() {
warned = {};
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = function() {};
if (true) {
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || (/^[s\W]*$/).test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
/***/ }
/******/ ])
});
; |
test/test_helper.js | bestii/Blog-App-React-Redux-Route | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
playground/topic/react/redux/counter/src/containers/Root.prod.js | yardfarmer/bone | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import CounterApp from './CounterApp';
export default class Root extends Component {
render() {
const { store } = this.props;
return (
<Provider store={store}>
<CounterApp />
</Provider>
);
}
}
|
src/store/auth/reducer.spec.js | asndev/webpack2-react-auth-starter | import React from 'react'; // eslint-disable-line no-unused-vars
import { authReducer, AuthState } from './reducer';
import { authActions } from './actions';
describe('store', () => {
describe('AuthReducer', () => {
it('should have the correct inital state', () => {
const state = authReducer(undefined, { type: 'foobar' });
expect(state.authenticated).toBe(false);
expect(state.uid).toBe(null);
expect(state.user).toBe(null);
});
it('should correctly handle successful login', () => {
const state = authReducer(undefined, {
payload: {
uid: '1234567',
name: 'Batman'
},
type: authActions.LOGIN_SUCCEEDED
});
expect(state.authenticated).toBe(true);
expect(state.uid).toBe('1234567');
expect(state.user.get('name')).toBe('Batman');
});
it('should correctly handle logout', () => {
const loggedIn = new AuthState().merge({
authenticated: true,
uid: '1234',
user: {}
});
const state = authReducer(loggedIn, {
type: authActions.LOGOUT_SUCCEEDED
});
expect(state.authenticated).toBe(false);
expect(state.uid).toBe(null);
expect(state.user).toBe(null);
});
});
});
|
src/scenes/App/components/Footer/index.js | jsza/tempus-website | import React from 'react'
import './styles.styl'
const Footer = ({ className, ...props }) =>
<footer
className={'App-footer ' + (className || '')}
{...props}
>
<ul className="links">
<li>
<a href="http://steampowered.com/">
<i className="fab fa-steam-symbol" /> Powered by Steam
</a>
</li>
<li>
<a href="https://tempus-apidocs.readthedocs.io/en/latest/">
API
</a>
</li>
</ul>
</footer>
export default Footer
|
ajax/libs/reactstrap/5.0.0/reactstrap.min.js | joeyparrish/cdnjs | (function(e,t){'object'==typeof exports&&'undefined'!=typeof module?t(exports,require('react'),require('react-dom'),require('react-popper'),require('react-transition-group/Transition')):'function'==typeof define&&define.amd?define(['exports','react','react-dom','react-popper','react-transition-group/Transition'],t):t(e.Reactstrap=e.Reactstrap||{},e.React,e.ReactDOM,e.ReactPopper || undefined,e.ReactTransitionGroup && e.ReactTransitionGroup.Transition || undefined)})(this,function(e,t,o,a,s){'use strict';function n(e,t){return t={exports:{}},e(t,t.exports),t.exports}function l(e){return function(){return e}}function r(e){if(null===e||e===void 0)throw new TypeError('Object.assign cannot be called with null or undefined');return Object(e)}function i(e){return null==e?void 0===e?te:ee:de&&de in Object(e)?d(e):c(e)}function d(e){var t=le.call(e,de),o=e[de];try{e[de]=void 0}catch(t){}var a=re.call(e);return t?e[de]=o:delete e[de],a}function c(e){return re.call(e)}function p(e){var t='undefined'==typeof e?'undefined':U(e);return null!=e&&('object'==t||'function'==t)}function u(){var e=document.createElement('div');e.style.position='absolute',e.style.top='-9999px',e.style.width='50px',e.style.height='50px',e.style.overflow='scroll',document.body.appendChild(e);var t=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),t}function g(e){document.body.style.paddingRight=0<e?e+'px':null}function m(){return document.body.clientWidth<window.innerWidth}function b(){var e=window.getComputedStyle(document.body,null);return parseInt(e&&e.getPropertyValue('padding-right')||0,10)}function f(){var e=u(),t=document.querySelectorAll('.fixed-top, .fixed-bottom, .is-fixed, .sticky-top')[0],o=t?parseInt(t.style.paddingRight||0,10):0;m()&&g(o+e)}function y(){var e=0<arguments.length&&arguments[0]!==void 0?arguments[0]:'',t=1<arguments.length&&arguments[1]!==void 0?arguments[1]:A;return t?e.split(' ').map(function(e){return t[e]||e}).join(' '):e}function v(e,t){var o={};return Object.keys(e).forEach(function(a){-1===t.indexOf(a)&&(o[a]=e[a])}),o}function h(e,t){for(var o,a=Array.isArray(t)?t:[t],s=a.length,n={};0<s;)s-=1,o=a[s],n[o]=e[o];return n}function N(e){pe[e]||('undefined'!=typeof console&&console.error(e),pe[e]=!0)}function T(e,t){return function(o,a,s){null!==o[a]&&'undefined'!=typeof o[a]&&N('"'+a+'" property of "'+s+'" has been deprecated.\n'+t);for(var n=arguments.length,l=Array(3<n?n-3:0),r=3;r<n;r++)l[r-3]=arguments[r];return e.apply(void 0,[o,a,s].concat(l))}}function k(e,t,o){if(!(e[t]instanceof Element))return new Error('Invalid prop `'+t+'` supplied to `'+o+'`. Expected prop to be an instance of Element. Validation failed.')}function E(e){if(ce(e))return e();if('string'==typeof e&&document){var t=document.querySelector(e);if(null===t&&(t=document.querySelector('#'+e)),null===t)throw new Error('The target \''+e+'\' could not be identified in the dom, tip: check spelling');return t}return e}function M(e){var t=e.tag,o=e.baseClass,a=e.baseClassActive,n=e.className,l=e.cssModule,r=e.children,i=J(e,['tag','baseClass','baseClassActive','className','cssModule','children']),d=h(i,ge),c=v(i,ge);return R.createElement(s,d,function(e){var s=y(Q(n,o,'entered'===e&&a),l);return R.createElement(t,X({className:s},c),r)})}function O(e){var t='undefined'==typeof e?'undefined':U(e);return!!e&&('object'==t||'function'==t)}function x(e){return!!e&&'object'==('undefined'==typeof e?'undefined':U(e))}function C(e){return'symbol'==('undefined'==typeof e?'undefined':U(e))||x(e)&&No.call(e)==go}function P(){}function _(e,t){var o=e.className,a=e.cssModule,s=e.tabId,n=e.tag,l=J(e,['className','cssModule','tabId','tag']),r=y(Q('tab-pane',o,{active:s===t.activeTabId}),a);return R.createElement(n,X({},l,{className:r}))}function w(e){var t=e.className,o=e.closeClassName,a=e.closeAriaLabel,s=e.cssModule,n=e.tag,l=e.color,r=e.isOpen,i=e.toggle,d=e.children,c=e.transition,p=J(e,['className','closeClassName','closeAriaLabel','cssModule','tag','color','isOpen','toggle','children','transition']),u=y(Q(t,'alert','alert-'+l,{"alert-dismissible":i}),s),g=y(Q('close',o),s);return R.createElement(M,X({},p,c,{tag:n,className:u,in:r,role:'alert'}),i?R.createElement('button',{type:'button',className:g,"aria-label":a,onClick:i},R.createElement('span',{"aria-hidden":'true'},'\xD7')):null,d)}function j(e){return Sa[e]||'collapse'}function I(e){return e.scrollHeight}var R='default'in t?t['default']:t;o=o&&'default'in o?o['default']:o,s=s&&'default'in s?s['default']:s;var D='undefined'==typeof window?'undefined'==typeof global?'undefined'==typeof self?{}:self:global:window,S=function(){};S.thatReturns=l,S.thatReturnsFalse=l(!1),S.thatReturnsTrue=l(!0),S.thatReturnsNull=l(null),S.thatReturnsThis=function(){return this},S.thatReturnsArgument=function(e){return e};var A,z=function(){},L=function(t,o,s,a,n,l,r,e){if(z(o),!t){var i;if(void 0===o)i=new Error('Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.');else{var d=[s,a,n,l,r,e],c=0;i=new Error(o.replace(/%s/g,function(){return d[c++]})),i.name='Invariant Violation'}throw i.framesToPop=1,i}},q=Object.getOwnPropertySymbols,H=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable,G=function(){try{if(!Object.assign)return!1;var e=new String('abc');if(e[5]='de','5'===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},o=0;10>o;o++)t['_'+String.fromCharCode(o)]=o;var a=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if('0123456789'!==a.join(''))return!1;var s={};return['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'].forEach(function(e){s[e]=e}),'abcdefghijklmnopqrst'===Object.keys(Object.assign({},s)).join('')}catch(e){return!1}}()?Object.assign:function(e){for(var t,o,a=r(e),n=1;n<arguments.length;n++){for(var s in t=Object(arguments[n]),t)H.call(t,s)&&(a[s]=t[s]);if(q){o=q(t);for(var l=0;l<o.length;l++)B.call(t,o[l])&&(a[o[l]]=t[o[l]])}}return a},U='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&'function'==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?'symbol':typeof e},F=function(e,t){if(!(e instanceof t))throw new TypeError('Cannot call a class as a function')},W=function(){function e(e,t){for(var o,a=0;a<t.length;a++)o=t[a],o.enumerable=o.enumerable||!1,o.configurable=!0,'value'in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}return function(t,o,a){return o&&e(t.prototype,o),a&&e(t,a),t}}(),K=function(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e},X=Object.assign||function(e){for(var t,o=1;o<arguments.length;o++)for(var a in t=arguments[o],t)Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},V=function(e,t){if('function'!=typeof t&&null!==t)throw new TypeError('Super expression must either be null or a function, not '+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},J=function(e,t){var o={};for(var a in e)0<=t.indexOf(a)||Object.prototype.hasOwnProperty.call(e,a)&&(o[a]=e[a]);return o},Y=function(e,t){if(!e)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t&&('object'==typeof t||'function'==typeof t)?t:e},$=function(){function e(e,t,o,a,s,n){n==='SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'||L(!1,'Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types')}function t(){return e}e.isRequired=e;var o={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return o.checkPropTypes=S,o.PropTypes=o,o},Z=n(function(e){e.exports=$()}),Q=n(function(e){(function(){function t(){for(var e,a=[],s=0;s<arguments.length;s++)if(e=arguments[s],e){var n='undefined'==typeof e?'undefined':U(e);if('string'===n||'number'===n)a.push(e);else if(Array.isArray(e))a.push(t.apply(null,e));else if('object'===n)for(var l in e)o.call(e,l)&&e[l]&&a.push(l)}return a.join(' ')}var o={}.hasOwnProperty;e.exports?e.exports=t:window.classNames=t})()}),ee='[object Null]',te='[object Undefined]',oe='object'==U(D)&&D&&D.Object===Object&&D,ae='object'==('undefined'==typeof self?'undefined':U(self))&&self&&self.Object===Object&&self,se=oe||ae||Function('return this')(),ne=Object.prototype,le=ne.hasOwnProperty,re=ne.toString,ie=se.Symbol,de=ie?ie.toStringTag:void 0,ce=function(e){if(!p(e))return!1;var t=i(e);return t=='[object Function]'||t=='[object GeneratorFunction]'||t=='[object AsyncFunction]'||t=='[object Proxy]'},pe={},ue={Fade:150,Collapse:350,Modal:300,Carousel:600},ge=['in','mountOnEnter','unmountOnExit','appear','enter','exit','timeout','onEnter','onEntering','onEntered','onExit','onExiting','onExited'],me={ENTERING:'entering',ENTERED:'entered',EXITING:'exiting',EXITED:'exited'},be={esc:27,space:32,tab:9,up:38,down:40},fe=['auto-start','auto','auto-end','top-start','top','top-end','right-start','right','right-end','bottom-end','bottom','bottom-start','left-end','left','left-start'],ye=!!('undefined'!=typeof window&&window.document&&window.document.createElement),ve=Object.freeze({getScrollbarWidth:u,setScrollbarWidth:g,isBodyOverflowing:m,getOriginalBodyPadding:b,conditionallyUpdateScrollbar:f,setGlobalCssModule:function(e){A=e},mapToCssModules:y,omit:v,pick:h,warnOnce:N,deprecated:T,DOMElement:k,getTarget:E,TransitionTimeouts:ue,TransitionPropTypeKeys:ge,TransitionStatuses:me,keyCodes:be,PopperPlacements:fe,canUseDOM:ye}),he={tag:Z.oneOfType([Z.func,Z.string]),fluid:Z.bool,className:Z.string,cssModule:Z.object},Ne=function(e){var t=e.className,o=e.cssModule,a=e.fluid,s=e.tag,n=J(e,['className','cssModule','fluid','tag']),l=y(Q(t,a?'container-fluid':'container'),o);return R.createElement(s,X({},n,{className:l}))};Ne.propTypes=he,Ne.defaultProps={tag:'div'};var Te={tag:Z.oneOfType([Z.func,Z.string]),noGutters:Z.bool,className:Z.string,cssModule:Z.object},ke=function(e){var t=e.className,o=e.cssModule,a=e.noGutters,s=e.tag,n=J(e,['className','cssModule','noGutters','tag']),l=y(Q(t,a?'no-gutters':null,'row'),o);return R.createElement(s,X({},n,{className:l}))};ke.propTypes=Te,ke.defaultProps={tag:'div'};var Ee=function(e){var t='undefined'==typeof e?'undefined':U(e);return!!e&&('object'==t||'function'==t)},Me=Z.oneOfType([Z.number,Z.string]),Oe=Z.oneOfType([Z.bool,Z.number,Z.string,Z.shape({size:Z.oneOfType([Z.bool,Z.number,Z.string]),push:T(Me,'Please use the prop "order"'),pull:T(Me,'Please use the prop "order"'),order:Me,offset:Me})]),xe={tag:Z.oneOfType([Z.func,Z.string]),xs:Oe,sm:Oe,md:Oe,lg:Oe,xl:Oe,className:Z.string,cssModule:Z.object,widths:Z.array},Ce=function(e,t,o){if(!0===o||''===o)return e?'col':'col-'+t;return'auto'===o?e?'col-auto':'col-'+t+'-auto':e?'col-'+o:'col-'+t+'-'+o},Pe=function(e){var t=e.className,o=e.cssModule,a=e.widths,s=e.tag,n=J(e,['className','cssModule','widths','tag']),l=[];a.forEach(function(t,a){var s=e[t];if(delete n[t],s||''===s){var r=!a;if(Ee(s)){var d,c=r?'-':'-'+t+'-',p=Ce(r,t,s.size);l.push(y(Q((d={},K(d,p,s.size||''===s.size),K(d,'order'+c+s.order,s.order||0===s.order),K(d,'offset'+c+s.offset,s.offset||0===s.offset),d)),o))}else{var u=Ce(r,t,s);l.push(u)}}}),l.length||l.push('col');var r=y(Q(t,l),o);return R.createElement(s,X({},n,{className:r}))};Pe.propTypes=xe,Pe.defaultProps={tag:'div',widths:['xs','sm','md','lg','xl']};var _e={light:Z.bool,dark:Z.bool,inverse:T(Z.bool,'Please use the prop "dark"'),full:Z.bool,fixed:Z.string,sticky:Z.string,color:Z.string,role:Z.string,tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object,toggleable:T(Z.oneOfType([Z.bool,Z.string]),'Please use the prop "expand"'),expand:Z.oneOfType([Z.bool,Z.string])},we=function(e){if(!1===e)return!1;return!0===e||'xs'===e?'navbar-expand':'navbar-expand-'+e},je={xs:'sm',sm:'md',md:'lg',lg:'xl'},Ie=function(e){if(e===void 0||'xl'===e)return!1;return!1===e?'navbar-expand':'navbar-expand-'+(!0===e?'sm':je[e]||e)},Re=function(e){var t,o=e.toggleable,a=e.expand,s=e.className,n=e.cssModule,l=e.light,r=e.dark,i=e.inverse,d=e.fixed,c=e.sticky,p=e.color,u=e.tag,g=J(e,['toggleable','expand','className','cssModule','light','dark','inverse','fixed','sticky','color','tag']),m=y(Q(s,'navbar',we(a)||Ie(o),(t={"navbar-light":l,"navbar-dark":i||r},K(t,'bg-'+p,p),K(t,'fixed-'+d,d),K(t,'sticky-'+c,c),t)),n);return R.createElement(u,X({},g,{className:m}))};Re.propTypes=_e,Re.defaultProps={tag:'nav',expand:!1};var De={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Se=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'navbar-brand'),o);return R.createElement(a,X({},s,{className:n}))};Se.propTypes=De,Se.defaultProps={tag:'a'};var Ae={tag:Z.oneOfType([Z.func,Z.string]),type:Z.string,className:Z.string,cssModule:Z.object,children:Z.node},ze=function(e){var t=e.className,o=e.cssModule,a=e.children,s=e.tag,n=J(e,['className','cssModule','children','tag']),l=y(Q(t,'navbar-toggler'),o);return R.createElement(s,X({},n,{className:l}),a||R.createElement('span',{className:y('navbar-toggler-icon',o)}))};ze.propTypes=Ae,ze.defaultProps={tag:'button',type:'button'};var Le={tabs:Z.bool,pills:Z.bool,vertical:Z.oneOfType([Z.bool,Z.string]),horizontal:Z.string,justified:Z.bool,fill:Z.bool,navbar:Z.bool,card:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},qe=function(e){if(!1===e)return!1;return!0===e||'xs'===e?'flex-column':'flex-'+e+'-column'},He=function(e){var t=e.className,o=e.cssModule,a=e.tabs,s=e.pills,n=e.vertical,l=e.horizontal,r=e.justified,i=e.fill,d=e.navbar,c=e.card,p=e.tag,u=J(e,['className','cssModule','tabs','pills','vertical','horizontal','justified','fill','navbar','card','tag']),g=y(Q(t,d?'navbar-nav':'nav',!!l&&'justify-content-'+l,qe(n),{"nav-tabs":a,"card-header-tabs":c&&a,"nav-pills":s,"card-header-pills":c&&s,"nav-justified":r,"nav-fill":i}),o);return R.createElement(p,X({},u,{className:g}))};He.propTypes=Le,He.defaultProps={tag:'ul',vertical:!1};var Be={tag:Z.oneOfType([Z.func,Z.string]),active:Z.bool,className:Z.string,cssModule:Z.object},Ge=function(e){var t=e.className,o=e.cssModule,a=e.active,s=e.tag,n=J(e,['className','cssModule','active','tag']),l=y(Q(t,'nav-item',!!a&&'active'),o);return R.createElement(s,X({},n,{className:l}))};Ge.propTypes=Be,Ge.defaultProps={tag:'li'};var Ue={disabled:Z.bool,dropup:T(Z.bool,'Please use the prop "direction" with the value "up".'),direction:Z.oneOf(['up','down','left','right']),group:Z.bool,isOpen:Z.bool,nav:Z.bool,active:Z.bool,addonType:Z.oneOfType([Z.bool,Z.oneOf(['prepend','append'])]),size:Z.string,tag:Z.string,toggle:Z.func,children:Z.node,className:Z.string,cssModule:Z.object,inNavbar:Z.bool},Fe={toggle:Z.func.isRequired,isOpen:Z.bool.isRequired,direction:Z.oneOf(['up','down','left','right']).isRequired,inNavbar:Z.bool.isRequired},We=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.addEvents=o.addEvents.bind(o),o.handleDocumentClick=o.handleDocumentClick.bind(o),o.handleKeyDown=o.handleKeyDown.bind(o),o.removeEvents=o.removeEvents.bind(o),o.toggle=o.toggle.bind(o),o}return V(t,e),W(t,[{key:'getChildContext',value:function(){return{toggle:this.props.toggle,isOpen:this.props.isOpen,direction:'down'===this.props.direction&&this.props.dropup?'up':this.props.direction,inNavbar:this.props.inNavbar}}},{key:'componentDidMount',value:function(){this.handleProps()}},{key:'componentDidUpdate',value:function(e){this.props.isOpen!==e.isOpen&&this.handleProps()}},{key:'componentWillUnmount',value:function(){this.removeEvents()}},{key:'getContainer',value:function(){return o.findDOMNode(this)}},{key:'addEvents',value:function(){var e=this;['click','touchstart','keyup'].forEach(function(t){return document.addEventListener(t,e.handleDocumentClick,!0)})}},{key:'removeEvents',value:function(){var e=this;['click','touchstart','keyup'].forEach(function(t){return document.removeEventListener(t,e.handleDocumentClick,!0)})}},{key:'handleDocumentClick',value:function(t){if(!(t&&(3===t.which||'keyup'===t.type&&t.which!==be.tab))){var e=this.getContainer();e.contains(t.target)&&e!==t.target&&('keyup'!==t.type||t.which===be.tab)||this.toggle(t)}}},{key:'handleKeyDown',value:function(t){if(!(-1===[be.esc,be.up,be.down,be.space].indexOf(t.which)||/button/i.test(t.target.tagName)&&t.which===be.space||/input|textarea/i.test(t.target.tagName))&&(t.preventDefault(),!this.props.disabled)){var e=this.getContainer();if(t.which===be.space&&this.props.isOpen&&e!==t.target&&t.target.click(),t.which===be.esc||!this.props.isOpen)return this.toggle(t),void e.querySelector('[aria-expanded]').focus();var o=y('dropdown-menu',this.props.cssModule),a=y('dropdown-item',this.props.cssModule),s=y('disabled',this.props.cssModule),n=e.querySelectorAll('.'+o+' .'+a+':not(.'+s+')');if(n.length){for(var l=-1,r=0;r<n.length;r+=1)if(n[r]===t.target){l=r;break}t.which===be.up&&0<l&&(l-=1),t.which===be.down&&l<n.length-1&&(l+=1),0>l&&(l=0),n[l].focus()}}}},{key:'handleProps',value:function(){this.props.isOpen?this.addEvents():this.removeEvents()}},{key:'toggle',value:function(t){return this.props.disabled?t&&t.preventDefault():this.props.toggle(t)}},{key:'render',value:function(){var e,t=v(this.props,['toggle','disabled','inNavbar','direction']),o=t.className,s=t.cssModule,n=t.dropup,l=t.isOpen,r=t.group,i=t.size,d=t.nav,c=t.active,p=t.addonType,u=J(t,['className','cssModule','dropup','isOpen','group','size','nav','active','addonType']),g='down'===this.props.direction&&n?'up':this.props.direction;u.tag=u.tag||(d?'li':'div');var m=y(Q(o,'down'!==g&&'drop'+g,d&&c&&'active',(e={},K(e,'input-group-'+p,p),K(e,'btn-group',r),K(e,'btn-group-'+i,!!i),K(e,'dropdown',!r&&!p),K(e,'show',l),K(e,'nav-item',d),e)),s);return R.createElement(a.Manager,X({},u,{className:m,onKeyDown:this.handleKeyDown}))}}]),t}(R.Component);We.propTypes=Ue,We.defaultProps={isOpen:!1,direction:'down',nav:!1,active:!1,addonType:!1,inNavbar:!1},We.childContextTypes=Fe;var Ke={tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),disabled:Z.bool,active:Z.bool,className:Z.string,cssModule:Z.object,onClick:Z.func,href:Z.any},Xe=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled?void t.preventDefault():void('#'===this.props.href&&t.preventDefault(),this.props.onClick&&this.props.onClick(t))}},{key:'render',value:function(){var e=this.props,t=e.className,o=e.cssModule,a=e.active,s=e.tag,n=e.innerRef,l=J(e,['className','cssModule','active','tag','innerRef']),r=y(Q(t,'nav-link',{disabled:l.disabled,active:a}),o);return R.createElement(s,X({},l,{ref:n,onClick:this.onClick,className:r}))}}]),t}(R.Component);Xe.propTypes=Ke,Xe.defaultProps={tag:'a'};var Ve={tag:Z.string,className:Z.string,cssModule:Z.object},Je=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'breadcrumb'),o);return R.createElement(a,X({},s,{className:n}))};Je.propTypes=Ve,Je.defaultProps={tag:'ol'};var Ye={tag:Z.oneOfType([Z.func,Z.string]),active:Z.bool,className:Z.string,cssModule:Z.object},$e=function(e){var t=e.className,o=e.cssModule,a=e.active,s=e.tag,n=J(e,['className','cssModule','active','tag']),l=y(Q(t,!!a&&'active','breadcrumb-item'),o);return R.createElement(s,X({},n,{className:l}))};$e.propTypes=Ye,$e.defaultProps={tag:'li'};var Ze={active:Z.bool,block:Z.bool,color:Z.string,disabled:Z.bool,outline:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),onClick:Z.func,size:Z.string,children:Z.node,className:Z.string,cssModule:Z.object},Qe=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled?void t.preventDefault():void(this.props.onClick&&this.props.onClick(t))}},{key:'render',value:function(){var e=this.props,t=e.active,o=e.block,a=e.className,s=e.cssModule,n=e.color,l=e.outline,r=e.size,i=e.tag,d=e.innerRef,c=J(e,['active','block','className','cssModule','color','outline','size','tag','innerRef']),p=y(Q(a,'btn','btn'+(l?'-outline':'')+'-'+n,!!r&&'btn-'+r,!!o&&'btn-block',{active:t,disabled:this.props.disabled}),s);return c.href&&'button'===i&&(i='a'),R.createElement(i,X({type:'button'===i&&c.onClick?'button':void 0},c,{className:p,ref:d,onClick:this.onClick}))}}]),t}(R.Component);Qe.propTypes=Ze,Qe.defaultProps={color:'secondary',tag:'button'};var et={children:Z.node},tt=function(e){return R.createElement(We,X({group:!0},e))};tt.propTypes=et;var ot={tag:Z.oneOfType([Z.func,Z.string]),"aria-label":Z.string,className:Z.string,cssModule:Z.object,role:Z.string,size:Z.string,vertical:Z.bool},at=function(e){var t=e.className,o=e.cssModule,a=e.size,s=e.vertical,n=e.tag,l=J(e,['className','cssModule','size','vertical','tag']),r=y(Q(t,!!a&&'btn-group-'+a,s?'btn-group-vertical':'btn-group'),o);return R.createElement(n,X({},l,{className:r}))};at.propTypes=ot,at.defaultProps={tag:'div',role:'group'};var st={tag:Z.oneOfType([Z.func,Z.string]),"aria-label":Z.string,className:Z.string,cssModule:Z.object,role:Z.string},nt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'btn-toolbar'),o);return R.createElement(a,X({},s,{className:n}))};nt.propTypes=st,nt.defaultProps={tag:'div',role:'toolbar'};var lt={children:Z.node,active:Z.bool,disabled:Z.bool,divider:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),header:Z.bool,onClick:Z.func,className:Z.string,cssModule:Z.object,toggle:Z.bool},rt={toggle:Z.func},it=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o.getTabIndex=o.getTabIndex.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled||this.props.header||this.props.divider?void t.preventDefault():void(this.props.onClick&&this.props.onClick(t),this.props.toggle&&this.context.toggle(t))}},{key:'getTabIndex',value:function(){return this.props.disabled||this.props.header||this.props.divider?'-1':'0'}},{key:'render',value:function(){var e=this.getTabIndex(),t=v(this.props,['toggle']),o=t.className,a=t.cssModule,s=t.divider,n=t.tag,l=t.header,r=t.active,i=J(t,['className','cssModule','divider','tag','header','active']),d=y(Q(o,{disabled:i.disabled,"dropdown-item":!s&&!l,active:r,"dropdown-header":l,"dropdown-divider":s}),a);return'button'===n&&(l?n='h6':s?n='div':i.href&&(n='a')),R.createElement(n,X({type:'button'===n&&(i.onClick||this.props.toggle)?'button':void 0},i,{tabIndex:e,className:d,onClick:this.onClick}))}}]),t}(R.Component);it.propTypes=lt,it.defaultProps={tag:'button',toggle:!0},it.contextTypes=rt;var dt={tag:Z.string,children:Z.node.isRequired,right:Z.bool,flip:Z.bool,className:Z.string,cssModule:Z.object},ct={isOpen:Z.bool.isRequired,direction:Z.oneOf(['up','down','left','right']).isRequired,inNavbar:Z.bool.isRequired},pt={flip:{enabled:!1}},ut={up:'top',left:'left',right:'right',down:'bottom'},gt=function(e,t){var o=e.className,s=e.cssModule,n=e.right,l=e.tag,r=e.flip,i=J(e,['className','cssModule','right','tag','flip']),d=y(Q(o,'dropdown-menu',{"dropdown-menu-right":n,show:t.isOpen}),s),c=l;if(t.isOpen&&!t.inNavbar){c=a.Popper;var p=ut[t.direction]||'bottom',u=n?'end':'start';i.placement=p+'-'+u,i.component=l,i.modifiers=r?void 0:pt}return R.createElement(c,X({tabIndex:'-1',role:'menu'},i,{"aria-hidden":!t.isOpen,className:d}))};gt.propTypes=dt,gt.defaultProps={tag:'div',flip:!0},gt.contextTypes=ct;var mt={caret:Z.bool,color:Z.string,children:Z.node,className:Z.string,cssModule:Z.object,disabled:Z.bool,onClick:Z.func,"aria-haspopup":Z.bool,split:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),nav:Z.bool},bt={isOpen:Z.bool.isRequired,toggle:Z.func.isRequired,inNavbar:Z.bool.isRequired},ft=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.onClick=o.onClick.bind(o),o}return V(t,e),W(t,[{key:'onClick',value:function(t){return this.props.disabled?void t.preventDefault():void(this.props.nav&&!this.props.tag&&t.preventDefault(),this.props.onClick&&this.props.onClick(t),this.context.toggle(t))}},{key:'render',value:function(){var e,t=this.props,o=t.className,s=t.color,n=t.cssModule,l=t.caret,r=t.split,i=t.nav,d=t.tag,c=J(t,['className','color','cssModule','caret','split','nav','tag']),p=c['aria-label']||'Toggle Dropdown',u=y(Q(o,{"dropdown-toggle":l||r,"dropdown-toggle-split":r,"nav-link":i}),n),g=c.children||R.createElement('span',{className:'sr-only'},p);return i&&!d?(e='a',c.href='#'):d?e=d:(e=Qe,c.color=s,c.cssModule=n),this.context.inNavbar?R.createElement(e,X({},c,{className:u,onClick:this.onClick,"aria-expanded":this.context.isOpen,children:g})):R.createElement(a.Target,X({},c,{className:u,component:e,onClick:this.onClick,"aria-expanded":this.context.isOpen,children:g}))}}]),t}(R.Component);ft.propTypes=mt,ft.defaultProps={"aria-haspopup":!0,color:'secondary'},ft.contextTypes=bt;var yt=X({},s.propTypes,{children:Z.oneOfType([Z.arrayOf(Z.node),Z.node]),tag:Z.oneOfType([Z.string,Z.func]),baseClass:Z.string,baseClassActive:Z.string,className:Z.string,cssModule:Z.object}),vt=X({},s.defaultProps,{tag:'div',baseClass:'fade',baseClassActive:'show',timeout:ue.Fade,appear:!0,enter:!0,exit:!0,in:!0});M.propTypes=yt,M.defaultProps=vt;var ht={color:Z.string,pill:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),children:Z.node,className:Z.string,cssModule:Z.object},Nt=function(e){var t=e.className,o=e.cssModule,a=e.color,s=e.pill,n=e.tag,l=J(e,['className','cssModule','color','pill','tag']),r=y(Q(t,'badge','badge-'+a,!!s&&'badge-pill'),o);return l.href&&'span'===n&&(n='a'),R.createElement(n,X({},l,{className:r}))};Nt.propTypes=ht,Nt.defaultProps={color:'secondary',pill:!1,tag:'span'};var Tt={tag:Z.oneOfType([Z.func,Z.string]),inverse:Z.bool,color:Z.string,block:T(Z.bool,'Please use the props "body"'),body:Z.bool,outline:Z.bool,className:Z.string,cssModule:Z.object},kt=function(e){var t=e.className,o=e.cssModule,a=e.color,s=e.block,n=e.body,l=e.inverse,r=e.outline,i=e.tag,d=J(e,['className','cssModule','color','block','body','inverse','outline','tag']),c=y(Q(t,'card',!!l&&'text-white',(s||n)&&'card-body',!!a&&(r?'border':'bg')+'-'+a),o);return R.createElement(i,X({},d,{className:c}))};kt.propTypes=Tt,kt.defaultProps={tag:'div'};var Et={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Mt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-group'),o);return R.createElement(a,X({},s,{className:n}))};Mt.propTypes=Et,Mt.defaultProps={tag:'div'};var Ot={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},xt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-deck'),o);return R.createElement(a,X({},s,{className:n}))};xt.propTypes=Ot,xt.defaultProps={tag:'div'};var Ct={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Pt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-columns'),o);return R.createElement(a,X({},s,{className:n}))};Pt.propTypes=Ct,Pt.defaultProps={tag:'div'};var _t={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},wt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-body'),o);return R.createElement(a,X({},s,{className:n}))};wt.propTypes=_t,wt.defaultProps={tag:'div'};var jt={tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},It=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=e.innerRef,n=J(e,['className','cssModule','tag','innerRef']),l=y(Q(t,'card-link'),o);return R.createElement(a,X({},n,{ref:s,className:l}))};It.propTypes=jt,It.defaultProps={tag:'a'};var Rt={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Dt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-footer'),o);return R.createElement(a,X({},s,{className:n}))};Dt.propTypes=Rt,Dt.defaultProps={tag:'div'};var St={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},At=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-header'),o);return R.createElement(a,X({},s,{className:n}))};At.propTypes=St,At.defaultProps={tag:'div'};var zt={tag:Z.oneOfType([Z.func,Z.string]),top:Z.bool,bottom:Z.bool,className:Z.string,cssModule:Z.object},Lt=function(e){var t=e.className,o=e.cssModule,a=e.top,s=e.bottom,n=e.tag,l=J(e,['className','cssModule','top','bottom','tag']),r='card-img';a&&(r='card-img-top'),s&&(r='card-img-bottom');var i=y(Q(t,r),o);return R.createElement(n,X({},l,{className:i}))};Lt.propTypes=zt,Lt.defaultProps={tag:'img'};var qt={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Ht=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-img-overlay'),o);return R.createElement(a,X({},s,{className:n}))};Ht.propTypes=qt,Ht.defaultProps={tag:'div'};var Bt=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={startAnimation:!1},o.onEnter=o.onEnter.bind(o),o.onEntering=o.onEntering.bind(o),o.onExit=o.onExit.bind(o),o.onExiting=o.onExiting.bind(o),o.onExited=o.onExited.bind(o),o}return V(t,e),W(t,[{key:'onEnter',value:function(e,t){this.setState({startAnimation:!1}),this.props.onEnter(e,t)}},{key:'onEntering',value:function(e,t){var o=e.offsetHeight;return this.setState({startAnimation:!0}),this.props.onEntering(e,t),o}},{key:'onExit',value:function(e){this.setState({startAnimation:!1}),this.props.onExit(e)}},{key:'onExiting',value:function(e){this.setState({startAnimation:!0}),e.dispatchEvent(new CustomEvent('slide.bs.carousel')),this.props.onExiting(e)}},{key:'onExited',value:function(e){e.dispatchEvent(new CustomEvent('slid.bs.carousel')),this.props.onExited(e)}},{key:'render',value:function(){var e=this,t=this.props,o=t.in,a=t.children,n=t.cssModule,l=t.slide,r=t.tag,i=t.className,d=J(t,['in','children','cssModule','slide','tag','className']);return R.createElement(s,X({},d,{enter:l,exit:l,in:o,onEnter:this.onEnter,onEntering:this.onEntering,onExit:this.onExit,onExiting:this.onExiting,onExited:this.onExited}),function(t){var o=e.context.direction,s=t===me.ENTERED||t===me.EXITING,l=(t===me.ENTERING||t===me.EXITING)&&e.state.startAnimation&&('right'===o?'carousel-item-left':'carousel-item-right'),d=t===me.ENTERING&&('right'===o?'carousel-item-next':'carousel-item-prev'),c=y(Q(i,'carousel-item',s&&'active',l,d),n);return R.createElement(r,{className:c},a)})}}]),t}(R.Component);Bt.propTypes=X({},s.propTypes,{tag:Z.oneOfType([Z.func,Z.string]),in:Z.bool,cssModule:Z.object,children:Z.node,slide:Z.bool,className:Z.string}),Bt.defaultProps=X({},s.defaultProps,{tag:'div',timeout:ue.Carousel,slide:!0}),Bt.contextTypes={direction:Z.string};var Gt=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.handleKeyPress=o.handleKeyPress.bind(o),o.renderItems=o.renderItems.bind(o),o.hoverStart=o.hoverStart.bind(o),o.hoverEnd=o.hoverEnd.bind(o),o.state={direction:'right',indicatorClicked:!1},o}return V(t,e),W(t,[{key:'getChildContext',value:function(){return{direction:this.state.direction}}},{key:'componentDidMount',value:function(){'carousel'===this.props.ride&&this.setInterval(),document.addEventListener('keyup',this.handleKeyPress)}},{key:'componentWillReceiveProps',value:function(e){this.setInterval(e),this.props.activeIndex+1===e.activeIndex?this.setState({direction:'right'}):this.props.activeIndex-1===e.activeIndex?this.setState({direction:'left'}):this.props.activeIndex>e.activeIndex?this.setState({direction:this.state.indicatorClicked?'left':'right'}):this.props.activeIndex!==e.activeIndex&&this.setState({direction:this.state.indicatorClicked?'right':'left'}),this.setState({indicatorClicked:!1})}},{key:'componentWillUnmount',value:function(){this.clearInterval(),document.removeEventListener('keyup',this.handleKeyPress)}},{key:'setInterval',value:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:this.props;this.clearInterval(),e.interval&&(this.cycleInterval=setInterval(function(){e.next()},parseInt(e.interval,10)))})},{key:'clearInterval',value:function(e){function t(){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(){clearInterval(this.cycleInterval)})},{key:'hoverStart',value:function(){if('hover'===this.props.pause&&this.clearInterval(),this.props.mouseEnter){var e;(e=this.props).mouseEnter.apply(e,arguments)}}},{key:'hoverEnd',value:function(){if('hover'===this.props.pause&&this.setInterval(),this.props.mouseLeave){var e;(e=this.props).mouseLeave.apply(e,arguments)}}},{key:'handleKeyPress',value:function(e){this.props.keyboard&&(37===e.keyCode?this.props.previous():39===e.keyCode&&this.props.next())}},{key:'renderItems',value:function(e,t){var o=this,a=this.props.slide;return R.createElement('div',{role:'listbox',className:t},e.map(function(e,t){var s=t===o.props.activeIndex;return R.cloneElement(e,{in:s,slide:a})}))}},{key:'render',value:function(){var t=this,e=this.props,o=e.children,a=e.cssModule,s=e.slide,n=e.className,l=y(Q(n,'carousel',s&&'slide'),a),r=y(Q('carousel-inner'),a),i=o.every(function(e){return e.type===Bt});if(i)return R.createElement('div',{className:l,onMouseEnter:this.hoverStart,onMouseLeave:this.hoverEnd},this.renderItems(o,r));if(o[0]instanceof Array){var d=o[0],c=o[1],p=o[2];return R.createElement('div',{className:l,onMouseEnter:this.hoverStart,onMouseLeave:this.hoverEnd},this.renderItems(d,r),c,p)}var u=o[0],g=R.cloneElement(u,{onClickHandler:function(o){'function'==typeof u.props.onClickHandler&&t.setState({indicatorClicked:!0},function(){return u.props.onClickHandler(o)})}}),m=o[1],b=o[2],f=o[3];return R.createElement('div',{className:l,onMouseEnter:this.hoverStart,onMouseLeave:this.hoverEnd},g,this.renderItems(m,r),b,f)}}]),t}(R.Component);Gt.propTypes={activeIndex:Z.number,next:Z.func.isRequired,previous:Z.func.isRequired,keyboard:Z.bool,pause:Z.oneOf(['hover',!1]),ride:Z.oneOf(['carousel']),interval:Z.oneOfType([Z.number,Z.string,Z.bool]),children:Z.array,mouseEnter:Z.func,mouseLeave:Z.func,slide:Z.bool,cssModule:Z.object,className:Z.string},Gt.defaultProps={interval:5e3,pause:'hover',keyboard:!0,slide:!0},Gt.childContextTypes={direction:Z.string};var Ut=function(e){var t=e.direction,o=e.onClickHandler,a=e.cssModule,s=e.directionText,n=e.className,l=y(Q(n,'carousel-control-'+t),a),r=y(Q('carousel-control-'+t+'-icon'),a),i=y(Q('sr-only'),a);return R.createElement('a',{className:l,role:'button',tabIndex:'0',onClick:function(t){t.preventDefault(),o()}},R.createElement('span',{className:r,"aria-hidden":'true'}),R.createElement('span',{className:i},s||t))};Ut.propTypes={direction:Z.oneOf(['prev','next']).isRequired,onClickHandler:Z.func.isRequired,cssModule:Z.object,directionText:Z.string,className:Z.string};var Ft=function(e){var t=e.items,o=e.activeIndex,a=e.cssModule,s=e.onClickHandler,n=e.className,l=y(Q(n,'carousel-indicators'),a),r=t.map(function(e,t){var n=y(Q({active:o===t}),a);return R.createElement('li',{key:''+(e.key||e.src)+e.caption+e.altText,onClick:function(o){o.preventDefault(),s(t)},className:n})});return R.createElement('ol',{className:l},r)};Ft.propTypes={items:Z.array.isRequired,activeIndex:Z.number.isRequired,cssModule:Z.object,onClickHandler:Z.func.isRequired,className:Z.string};var Wt=function(e){var t=e.captionHeader,o=e.captionText,a=e.cssModule,s=e.className,n=y(Q(s,'carousel-caption','d-none','d-md-block'),a);return R.createElement('div',{className:n},R.createElement('h3',null,t),R.createElement('p',null,o))};Wt.propTypes={captionHeader:Z.string,captionText:Z.string.isRequired,cssModule:Z.object,className:Z.string};var Kt={items:Z.array.isRequired,indicators:Z.bool,controls:Z.bool,autoPlay:Z.bool,activeIndex:Z.number,next:Z.func,previous:Z.func,goToIndex:Z.func},Xt=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.animating=!1,o.state={activeIndex:0},o.next=o.next.bind(o),o.previous=o.previous.bind(o),o.goToIndex=o.goToIndex.bind(o),o.onExiting=o.onExiting.bind(o),o.onExited=o.onExited.bind(o),o}return V(t,e),W(t,[{key:'onExiting',value:function(){this.animating=!0}},{key:'onExited',value:function(){this.animating=!1}},{key:'next',value:function(){if(!this.animating){var e=this.state.activeIndex===this.props.items.length-1?0:this.state.activeIndex+1;this.setState({activeIndex:e})}}},{key:'previous',value:function(){if(!this.animating){var e=0===this.state.activeIndex?this.props.items.length-1:this.state.activeIndex-1;this.setState({activeIndex:e})}}},{key:'goToIndex',value:function(e){this.animating||this.setState({activeIndex:e})}},{key:'render',value:function(){var e=this,t=this.props,o=t.autoPlay,a=t.indicators,s=t.controls,n=t.items,l=t.goToIndex,r=J(t,['autoPlay','indicators','controls','items','goToIndex']),i=this.state.activeIndex,d=n.map(function(t){return R.createElement(Bt,{onExiting:e.onExiting,onExited:e.onExited,key:t.src},R.createElement('img',{src:t.src,alt:t.altText}),R.createElement(Wt,{captionText:t.caption,captionHeader:t.caption}))});return R.createElement(Gt,X({activeIndex:i,next:this.next,previous:this.previous,ride:o?'carousel':void 0},r),a&&R.createElement(Ft,{items:n,activeIndex:r.activeIndex||i,onClickHandler:l||this.goToIndex}),d,s&&R.createElement(Ut,{direction:'prev',directionText:'Previous',onClickHandler:r.previous||this.previous}),s&&R.createElement(Ut,{direction:'next',directionText:'Next',onClickHandler:r.next||this.next}))}}]),t}(t.Component);Xt.propTypes=Kt,Xt.defaultProps={controls:!0,indicators:!0,autoPlay:!0};var Vt={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Jt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-subtitle'),o);return R.createElement(a,X({},s,{className:n}))};Jt.propTypes=Vt,Jt.defaultProps={tag:'h6'};var Yt={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},$t=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-text'),o);return R.createElement(a,X({},s,{className:n}))};$t.propTypes=Yt,$t.defaultProps={tag:'p'};var Zt={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Qt=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'card-title'),o);return R.createElement(a,X({},s,{className:n}))};Qt.propTypes=Zt,Qt.defaultProps={tag:'h5'};var eo={children:Z.node.isRequired,className:Z.string,placement:Z.string,placementPrefix:Z.string,hideArrow:Z.bool,tag:Z.string,isOpen:Z.bool.isRequired,cssModule:Z.object,offset:Z.oneOfType([Z.string,Z.number]),fallbackPlacement:Z.oneOfType([Z.string,Z.array]),flip:Z.bool,container:Z.oneOfType([Z.string,Z.func,k]),target:Z.oneOfType([Z.string,Z.func,k]).isRequired,modifiers:Z.object},to={popperManager:Z.object.isRequired},oo=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.handlePlacementChange=o.handlePlacementChange.bind(o),o.setTargetNode=o.setTargetNode.bind(o),o.getTargetNode=o.getTargetNode.bind(o),o.state={},o}return V(t,e),W(t,[{key:'getChildContext',value:function(){return{popperManager:{setTargetNode:this.setTargetNode,getTargetNode:this.getTargetNode}}}},{key:'componentDidMount',value:function(){this.handleProps()}},{key:'componentDidUpdate',value:function(e){this.props.isOpen===e.isOpen?this._element&&this.renderIntoSubtree():this.handleProps()}},{key:'componentWillUnmount',value:function(){this.hide()}},{key:'setTargetNode',value:function(e){this.targetNode=e}},{key:'getTargetNode',value:function(){return this.targetNode}},{key:'getContainerNode',value:function(){return E(this.props.container)}},{key:'handlePlacementChange',value:function(e){return this.state.placement!==e.placement&&this.setState({placement:e.placement}),e}},{key:'handleProps',value:function(){'inline'!==this.props.container&&(this.props.isOpen?this.show():this.hide())}},{key:'hide',value:function(){this._element&&(this.getContainerNode().removeChild(this._element),o.unmountComponentAtNode(this._element),this._element=null)}},{key:'show',value:function(){this._element=document.createElement('div'),this.getContainerNode().appendChild(this._element),this.renderIntoSubtree(),this._element.childNodes&&this._element.childNodes[0]&&this._element.childNodes[0].focus&&this._element.childNodes[0].focus()}},{key:'renderIntoSubtree',value:function(){o.unstable_renderSubtreeIntoContainer(this,this.renderChildren(),this._element)}},{key:'renderChildren',value:function(){var e=this.props,t=e.cssModule,o=e.children,s=e.isOpen,n=e.flip,l=e.target,r=e.offset,i=e.fallbackPlacement,d=e.placementPrefix,c=e.hideArrow,p=e.className,u=e.tag,g=e.container,m=e.modifiers,b=J(e,['cssModule','children','isOpen','flip','target','offset','fallbackPlacement','placementPrefix','hideArrow','className','tag','container','modifiers']),f=y('arrow',t),v=(this.state.placement||b.placement).split('-')[0],h=y(Q(p,d?d+'-'+v:v),this.props.cssModule),N=X({offset:{offset:r},flip:{enabled:n,behavior:i},update:{enabled:!0,order:950,fn:this.handlePlacementChange}},m);return R.createElement(a.Popper,X({modifiers:N},b,{component:u,className:h}),o,!c&&R.createElement(a.Arrow,{className:f}))}},{key:'render',value:function(){return this.setTargetNode(E(this.props.target)),'inline'===this.props.container?this.props.isOpen?this.renderChildren():null:null}}]),t}(R.Component);oo.propTypes=eo,oo.defaultProps={placement:'auto',hideArrow:!1,isOpen:!1,offset:0,fallbackPlacement:'flip',flip:!0,container:'body',modifiers:{}},oo.childContextTypes=to;var ao=function(e,t){return t.popperManager.setTargetNode(E(e.target)),null};ao.contextTypes={popperManager:Z.object.isRequired},ao.propTypes={target:Z.oneOfType([Z.string,Z.func,k]).isRequired};var so={placement:Z.oneOf(fe),target:Z.oneOfType([Z.string,Z.func,k]).isRequired,container:Z.oneOfType([Z.string,Z.func,k]),isOpen:Z.bool,disabled:Z.bool,hideArrow:Z.bool,className:Z.string,innerClassName:Z.string,placementPrefix:Z.string,cssModule:Z.object,toggle:Z.func,delay:Z.oneOfType([Z.shape({show:Z.number,hide:Z.number}),Z.number]),modifiers:Z.object},no={show:0,hide:0},lo=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.addTargetEvents=o.addTargetEvents.bind(o),o.handleDocumentClick=o.handleDocumentClick.bind(o),o.removeTargetEvents=o.removeTargetEvents.bind(o),o.getRef=o.getRef.bind(o),o.toggle=o.toggle.bind(o),o.show=o.show.bind(o),o.hide=o.hide.bind(o),o}return V(t,e),W(t,[{key:'componentDidMount',value:function(){this._target=E(this.props.target),this.handleProps()}},{key:'componentDidUpdate',value:function(){this.handleProps()}},{key:'componentWillUnmount',value:function(){this.clearShowTimeout(),this.clearHideTimeout(),this.removeTargetEvents()}},{key:'getRef',value:function(e){this._popover=e}},{key:'getDelay',value:function(e){var t=this.props.delay;return'object'===('undefined'==typeof t?'undefined':U(t))?isNaN(t[e])?no[e]:t[e]:t}},{key:'handleProps',value:function(){this.props.isOpen?this.show():this.hide()}},{key:'show',value:function(){this.clearHideTimeout(),this.addTargetEvents(),this.props.isOpen||(this.clearShowTimeout(),this._showTimeout=setTimeout(this.toggle,this.getDelay('show')))}},{key:'hide',value:function(){this.clearShowTimeout(),this.removeTargetEvents(),this.props.isOpen&&(this.clearHideTimeout(),this._hideTimeout=setTimeout(this.toggle,this.getDelay('hide')))}},{key:'clearShowTimeout',value:function(){clearTimeout(this._showTimeout),this._showTimeout=void 0}},{key:'clearHideTimeout',value:function(){clearTimeout(this._hideTimeout),this._hideTimeout=void 0}},{key:'handleDocumentClick',value:function(t){t.target===this._target||this._target.contains(t.target)||t.target===this._popover||this._popover&&this._popover.contains(t.target)||(this._hideTimeout&&this.clearHideTimeout(),this.props.isOpen&&this.toggle(t))}},{key:'addTargetEvents',value:function(){var e=this;['click','touchstart'].forEach(function(t){return document.addEventListener(t,e.handleDocumentClick,!0)})}},{key:'removeTargetEvents',value:function(){var e=this;['click','touchstart'].forEach(function(t){return document.removeEventListener(t,e.handleDocumentClick,!0)})}},{key:'toggle',value:function(t){return this.props.disabled?t&&t.preventDefault():this.props.toggle(t)}},{key:'render',value:function(){if(!this.props.isOpen)return null;var e=v(this.props,Object.keys(so)),t=y(Q('popover-inner',this.props.innerClassName),this.props.cssModule),o=y(Q('popover','show',this.props.className),this.props.cssModule);return R.createElement(oo,{className:o,target:this.props.target,isOpen:this.props.isOpen,hideArrow:this.props.hideArrow,placement:this.props.placement,placementPrefix:this.props.placementPrefix,container:this.props.container,modifiers:this.props.modifiers},R.createElement('div',X({},e,{className:t,ref:this.getRef})))}}]),t}(R.Component);lo.propTypes=so,lo.defaultProps={isOpen:!1,hideArrow:!1,placement:'right',placementPrefix:'bs-popover',delay:no,toggle:function(){}};var ro={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},io=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'popover-header'),o);return R.createElement(a,X({},s,{className:n}))};io.propTypes=ro,io.defaultProps={tag:'h3'};var co={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},po=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'popover-body'),o);return R.createElement(a,X({},s,{className:n}))};po.propTypes=co,po.defaultProps={tag:'div'};var uo=0/0,go='[object Symbol]',mo=/^\s+|\s+$/g,bo=/^[-+]0x[0-9a-f]+$/i,fo=/^0b[01]+$/i,yo=/^0o[0-7]+$/i,vo=parseInt,ho=Object.prototype,No=ho.toString,To=function(e){if('number'==typeof e)return e;if(C(e))return uo;if(O(e)){var t='function'==typeof e.valueOf?e.valueOf():e;e=O(t)?t+'':t}if('string'!=typeof e)return 0===e?e:+e;e=e.replace(mo,'');var o=fo.test(e);return o||yo.test(e)?vo(e.slice(2),o?2:8):bo.test(e)?uo:+e},ko={children:Z.node,bar:Z.bool,multi:Z.bool,tag:Z.string,value:Z.oneOfType([Z.string,Z.number]),max:Z.oneOfType([Z.string,Z.number]),animated:Z.bool,striped:Z.bool,color:Z.string,className:Z.string,barClassName:Z.string,cssModule:Z.object},Eo=function(e){var t=e.children,o=e.className,a=e.barClassName,s=e.cssModule,n=e.value,l=e.max,r=e.animated,i=e.striped,d=e.color,c=e.bar,p=e.multi,u=e.tag,g=J(e,['children','className','barClassName','cssModule','value','max','animated','striped','color','bar','multi','tag']),m=100*(To(n)/To(l)),b=y(Q(o,'progress'),s),f=y(Q('progress-bar',c?o||a:a,r?'progress-bar-animated':null,d?'bg-'+d:null,i||r?'progress-bar-striped':null),s),v=p?t:R.createElement('div',{className:f,style:{width:m+'%'},role:'progressbar',"aria-valuenow":n,"aria-valuemin":'0',"aria-valuemax":l,children:t});return c?v:R.createElement(u,X({},g,{className:b,children:v}))};Eo.propTypes=ko,Eo.defaultProps={tag:'div',value:0,max:100};var Mo={children:Z.node.isRequired,node:Z.any},Oo=function(e){function t(){return F(this,t),Y(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return V(t,e),W(t,[{key:'componentWillUnmount',value:function(){this.defaultNode&&document.body.removeChild(this.defaultNode),this.defaultNode=null}},{key:'render',value:function(){return ye?(this.props.node||this.defaultNode||(this.defaultNode=document.createElement('div'),document.body.appendChild(this.defaultNode)),o.createPortal(this.props.children,this.props.node||this.defaultNode)):null}}]),t}(R.Component);Oo.propTypes=Mo;var xo=Z.shape(M.propTypes),Co={isOpen:Z.bool,autoFocus:Z.bool,centered:Z.bool,size:Z.string,toggle:Z.func,keyboard:Z.bool,role:Z.string,labelledBy:Z.string,backdrop:Z.oneOfType([Z.bool,Z.oneOf(['static'])]),onEnter:Z.func,onExit:Z.func,onOpened:Z.func,onClosed:Z.func,children:Z.node,className:Z.string,wrapClassName:Z.string,modalClassName:Z.string,backdropClassName:Z.string,contentClassName:Z.string,external:Z.node,fade:Z.bool,cssModule:Z.object,zIndex:Z.oneOfType([Z.number,Z.string]),backdropTransition:xo,modalTransition:xo},Po=Object.keys(Co),_o={isOpen:!1,autoFocus:!0,centered:!1,role:'dialog',backdrop:!0,keyboard:!0,zIndex:1050,fade:!0,onOpened:P,onClosed:P,modalTransition:{timeout:ue.Modal},backdropTransition:{mountOnEnter:!0,timeout:ue.Fade}},wo=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o._element=null,o._originalBodyPadding=null,o.handleBackdropClick=o.handleBackdropClick.bind(o),o.handleEscape=o.handleEscape.bind(o),o.onOpened=o.onOpened.bind(o),o.onClosed=o.onClosed.bind(o),o.state={isOpen:e.isOpen},e.isOpen&&o.init(),o}return V(t,e),W(t,[{key:'componentDidMount',value:function(){this.props.onEnter&&this.props.onEnter(),this.state.isOpen&&this.props.autoFocus&&this.setFocus(),this._isMounted=!0}},{key:'componentWillReceiveProps',value:function(e){e.isOpen&&!this.props.isOpen&&this.setState({isOpen:e.isOpen})}},{key:'componentWillUpdate',value:function(e,t){t.isOpen&&!this.state.isOpen&&this.init()}},{key:'componentDidUpdate',value:function(e,t){this.props.autoFocus&&this.state.isOpen&&!t.isOpen&&this.setFocus()}},{key:'componentWillUnmount',value:function(){this.props.onExit&&this.props.onExit(),this.state.isOpen&&this.destroy(),this._isMounted=!1}},{key:'onOpened',value:function(e,t){this.props.onOpened(),(this.props.modalTransition.onEntered||P)(e,t)}},{key:'onClosed',value:function(e){this.props.onClosed(),(this.props.modalTransition.onExited||P)(e),this.destroy(),this._isMounted&&this.setState({isOpen:!1})}},{key:'setFocus',value:function(){this._dialog&&this._dialog.parentNode&&'function'==typeof this._dialog.parentNode.focus&&this._dialog.parentNode.focus()}},{key:'handleBackdropClick',value:function(t){if(t.stopPropagation(),this.props.isOpen&&!0===this.props.backdrop){var e=this._dialog;t.target&&!e.contains(t.target)&&this.props.toggle&&this.props.toggle(t)}}},{key:'handleEscape',value:function(t){this.props.isOpen&&this.props.keyboard&&27===t.keyCode&&this.props.toggle&&this.props.toggle(t)}},{key:'init',value:function(){this._element=document.createElement('div'),this._element.setAttribute('tabindex','-1'),this._element.style.position='relative',this._element.style.zIndex=this.props.zIndex,this._originalBodyPadding=b(),f(),document.body.appendChild(this._element),this.bodyClassAdded||(document.body.className=Q(document.body.className,y('modal-open',this.props.cssModule)),this.bodyClassAdded=!0)}},{key:'destroy',value:function(){if(this._element&&(document.body.removeChild(this._element),this._element=null),this.bodyClassAdded){var e=y('modal-open',this.props.cssModule),t=new RegExp('(^| )'+e+'( |$)');document.body.className=document.body.className.replace(t,' ').trim(),this.bodyClassAdded=!1}g(this._originalBodyPadding)}},{key:'renderModalDialog',value:function(){var e,t=this,o=v(this.props,Po),a='modal-dialog';return R.createElement('div',X({},o,{className:y(Q(a,this.props.className,(e={},K(e,'modal-'+this.props.size,this.props.size),K(e,a+'-centered',this.props.centered),e)),this.props.cssModule),role:'document',ref:function(e){t._dialog=e}}),R.createElement('div',{className:y(Q('modal-content',this.props.contentClassName),this.props.cssModule)},this.props.children))}},{key:'render',value:function(){if(this.state.isOpen){var e=this.props,t=e.wrapClassName,o=e.modalClassName,a=e.backdropClassName,s=e.cssModule,n=e.isOpen,l=e.backdrop,r=e.role,i=e.labelledBy,d=e.external,c={onClick:this.handleBackdropClick,onKeyUp:this.handleEscape,style:{display:'block'},"aria-labelledby":i,role:r,tabIndex:'-1'},p=this.props.fade,u=X({},M.defaultProps,this.props.modalTransition,{baseClass:p?this.props.modalTransition.baseClass:'',timeout:p?this.props.modalTransition.timeout:0}),g=X({},M.defaultProps,this.props.backdropTransition,{baseClass:p?this.props.backdropTransition.baseClass:'',timeout:p?this.props.backdropTransition.timeout:0});return R.createElement(Oo,{node:this._element},R.createElement('div',{className:y(t)},R.createElement(M,X({},c,u,{in:n,onEntered:this.onOpened,onExited:this.onClosed,cssModule:s,className:y(Q('modal',o),s)}),d,this.renderModalDialog()),R.createElement(M,X({},g,{in:n&&!!l,cssModule:s,className:y(Q('modal-backdrop',a),s)}))))}return null}}]),t}(R.Component);wo.propTypes=Co,wo.defaultProps=_o;var jo={tag:Z.oneOfType([Z.func,Z.string]),wrapTag:Z.oneOfType([Z.func,Z.string]),toggle:Z.func,className:Z.string,cssModule:Z.object,children:Z.node,closeAriaLabel:Z.string},Io=function(e){var t,o=e.className,a=e.cssModule,s=e.children,n=e.toggle,l=e.tag,r=e.wrapTag,i=e.closeAriaLabel,d=J(e,['className','cssModule','children','toggle','tag','wrapTag','closeAriaLabel']),c=y(Q(o,'modal-header'),a);return n&&(t=R.createElement('button',{type:'button',onClick:n,className:y('close',a),"aria-label":i},R.createElement('span',{"aria-hidden":'true'},'\xD7'))),R.createElement(r,X({},d,{className:c}),R.createElement(l,{className:y('modal-title',a)},s),t)};Io.propTypes=jo,Io.defaultProps={tag:'h5',wrapTag:'div',closeAriaLabel:'Close'};var Ro={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Do=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'modal-body'),o);return R.createElement(a,X({},s,{className:n}))};Do.propTypes=Ro,Do.defaultProps={tag:'div'};var So={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Ao=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'modal-footer'),o);return R.createElement(a,X({},s,{className:n}))};Ao.propTypes=So,Ao.defaultProps={tag:'div'};var zo={placement:Z.oneOf(fe),target:Z.oneOfType([Z.string,Z.func,k]).isRequired,container:Z.oneOfType([Z.string,Z.func,k]),isOpen:Z.bool,disabled:Z.bool,hideArrow:Z.bool,className:Z.string,innerClassName:Z.string,cssModule:Z.object,toggle:Z.func,autohide:Z.bool,placementPrefix:Z.string,delay:Z.oneOfType([Z.shape({show:Z.number,hide:Z.number}),Z.number]),modifiers:Z.object},Lo={show:0,hide:250},qo=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.addTargetEvents=o.addTargetEvents.bind(o),o.handleDocumentClick=o.handleDocumentClick.bind(o),o.removeTargetEvents=o.removeTargetEvents.bind(o),o.toggle=o.toggle.bind(o),o.onMouseOverTooltip=o.onMouseOverTooltip.bind(o),o.onMouseLeaveTooltip=o.onMouseLeaveTooltip.bind(o),o.onMouseOverTooltipContent=o.onMouseOverTooltipContent.bind(o),o.onMouseLeaveTooltipContent=o.onMouseLeaveTooltipContent.bind(o),o.show=o.show.bind(o),o.hide=o.hide.bind(o),o}return V(t,e),W(t,[{key:'componentDidMount',value:function(){this._target=E(this.props.target),this.addTargetEvents()}},{key:'componentWillUnmount',value:function(){this.removeTargetEvents()}},{key:'onMouseOverTooltip',value:function(){this._hideTimeout&&this.clearHideTimeout(),this._showTimeout=setTimeout(this.show,this.getDelay('show'))}},{key:'onMouseLeaveTooltip',value:function(){this._showTimeout&&this.clearShowTimeout(),this._hideTimeout=setTimeout(this.hide,this.getDelay('hide'))}},{key:'onMouseOverTooltipContent',value:function(){this.props.autohide||this._hideTimeout&&this.clearHideTimeout()}},{key:'onMouseLeaveTooltipContent',value:function(){this.props.autohide||(this._showTimeout&&this.clearShowTimeout(),this._hideTimeout=setTimeout(this.hide,this.getDelay('hide')))}},{key:'getDelay',value:function(e){var t=this.props.delay;return'object'===('undefined'==typeof t?'undefined':U(t))?isNaN(t[e])?Lo[e]:t[e]:t}},{key:'show',value:function(){this.props.isOpen||(this.clearShowTimeout(),this.toggle())}},{key:'hide',value:function(){this.props.isOpen&&(this.clearHideTimeout(),this.toggle())}},{key:'clearShowTimeout',value:function(){clearTimeout(this._showTimeout),this._showTimeout=void 0}},{key:'clearHideTimeout',value:function(){clearTimeout(this._hideTimeout),this._hideTimeout=void 0}},{key:'handleDocumentClick',value:function(t){(t.target===this._target||this._target.contains(t.target))&&(this._hideTimeout&&this.clearHideTimeout(),!this.props.isOpen&&this.toggle())}},{key:'addTargetEvents',value:function(){var e=this;this._target.addEventListener('mouseover',this.onMouseOverTooltip,!0),this._target.addEventListener('mouseout',this.onMouseLeaveTooltip,!0),['click','touchstart'].forEach(function(t){return document.addEventListener(t,e.handleDocumentClick,!0)})}},{key:'removeTargetEvents',value:function(){var e=this;this._target.removeEventListener('mouseover',this.onMouseOverTooltip,!0),this._target.removeEventListener('mouseout',this.onMouseLeaveTooltip,!0),['click','touchstart'].forEach(function(t){return document.removeEventListener(t,e.handleDocumentClick,!0)})}},{key:'toggle',value:function(t){return this.props.disabled?t&&t.preventDefault():this.props.toggle()}},{key:'render',value:function(){if(!this.props.isOpen)return null;var e=v(this.props,Object.keys(zo)),t=y(Q('tooltip-inner',this.props.innerClassName),this.props.cssModule),o=y(Q('tooltip','show',this.props.className),this.props.cssModule);return R.createElement(oo,{className:o,target:this.props.target,isOpen:this.props.isOpen,hideArrow:this.props.hideArrow,placement:this.props.placement,placementPrefix:this.props.placementPrefix,container:this.props.container,modifiers:this.props.modifiers},R.createElement('div',X({},e,{className:t,onMouseOver:this.onMouseOverTooltipContent,onMouseLeave:this.onMouseLeaveTooltipContent})))}}]),t}(R.Component);qo.propTypes=zo,qo.defaultProps={isOpen:!1,hideArrow:!1,placement:'top',placementPrefix:'bs-tooltip',delay:Lo,autohide:!0,toggle:function(){}};var Ho={className:Z.string,cssModule:Z.object,size:Z.string,bordered:Z.bool,striped:Z.bool,inverse:T(Z.bool,'Please use the prop "dark"'),dark:Z.bool,hover:Z.bool,responsive:Z.oneOfType([Z.bool,Z.string]),tag:Z.oneOfType([Z.func,Z.string]),responsiveTag:Z.oneOfType([Z.func,Z.string])},Bo=function(e){var t=e.className,o=e.cssModule,a=e.size,s=e.bordered,n=e.striped,l=e.inverse,r=e.dark,i=e.hover,d=e.responsive,c=e.tag,p=e.responsiveTag,u=J(e,['className','cssModule','size','bordered','striped','inverse','dark','hover','responsive','tag','responsiveTag']),g=y(Q(t,'table',!!a&&'table-'+a,!!s&&'table-bordered',!!n&&'table-striped',(r||l)&&'table-dark',!!i&&'table-hover'),o),m=R.createElement(c,X({},u,{className:g}));if(d){var b=!0===d?'table-responsive':'table-responsive-'+d;return R.createElement(p,{className:b},m)}return m};Bo.propTypes=Ho,Bo.defaultProps={tag:'table',responsiveTag:'div'};var Go={tag:Z.oneOfType([Z.func,Z.string]),flush:Z.bool,className:Z.string,cssModule:Z.object},Uo=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=e.flush,n=J(e,['className','cssModule','tag','flush']),l=y(Q(t,'list-group',!!s&&'list-group-flush'),o);return R.createElement(a,X({},n,{className:l}))};Uo.propTypes=Go,Uo.defaultProps={tag:'ul'};var Fo={children:Z.node,inline:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},Wo=function(e){var t=e.className,o=e.cssModule,a=e.inline,s=e.tag,n=e.innerRef,l=J(e,['className','cssModule','inline','tag','innerRef']),r=y(Q(t,!!a&&'form-inline'),o);return R.createElement(s,X({},l,{ref:n,className:r}))};Wo.propTypes=Fo,Wo.defaultProps={tag:'form'};var Ko={children:Z.node,tag:Z.string,className:Z.string,cssModule:Z.object,valid:Z.bool},Xo=function(e){var t=e.className,o=e.cssModule,a=e.valid,s=e.tag,n=J(e,['className','cssModule','valid','tag']),l=y(Q(t,a?'valid-feedback':'invalid-feedback'),o);return R.createElement(s,X({},n,{className:l}))};Xo.propTypes=Ko,Xo.defaultProps={tag:'div',valid:void 0};var Vo={children:Z.node,row:Z.bool,check:Z.bool,inline:Z.bool,disabled:Z.bool,tag:Z.string,className:Z.string,cssModule:Z.object},Jo=function(e){var t=e.className,o=e.cssModule,a=e.row,s=e.disabled,n=e.check,l=e.inline,r=e.tag,i=J(e,['className','cssModule','row','disabled','check','inline','tag']),d=y(Q(t,!!a&&'row',n?'form-check':'form-group',n&&l&&'form-check-inline',n&&s&&'disabled'),o);return R.createElement(r,X({},i,{className:d}))};Jo.propTypes=Vo,Jo.defaultProps={tag:'div'};var Yo={children:Z.node,inline:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),color:Z.string,className:Z.string,cssModule:Z.object},$o=function(e){var t=e.className,o=e.cssModule,a=e.inline,s=e.color,n=e.tag,l=J(e,['className','cssModule','inline','color','tag']),r=y(Q(t,!a&&'form-text',!!s&&'text-'+s),o);return R.createElement(n,X({},l,{className:r}))};$o.propTypes=Yo,$o.defaultProps={tag:'small',color:'muted'};var Zo={children:Z.node,type:Z.string,size:Z.string,bsSize:Z.string,state:T(Z.string,'Please use the props "valid" and "invalid" to indicate the state.'),valid:Z.bool,invalid:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),innerRef:Z.oneOfType([Z.func,Z.string]),static:T(Z.bool,'Please use the prop "plaintext"'),plaintext:Z.bool,addon:Z.bool,className:Z.string,cssModule:Z.object},Qo=function(e){function t(){return F(this,t),Y(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return V(t,e),W(t,[{key:'render',value:function(){var e=this.props,t=e.className,o=e.cssModule,a=e.type,s=e.bsSize,n=e.state,l=e.valid,r=e.invalid,i=e.tag,d=e.addon,c=e.static,p=e.plaintext,u=e.innerRef,g=J(e,['className','cssModule','type','bsSize','state','valid','invalid','tag','addon','static','plaintext','innerRef']),m=-1<['radio','checkbox'].indexOf(a),b=/\D/g,f=i||('select'===a||'textarea'===a?a:'input'),v='form-control';p||c?(v+='-plaintext',f=i||'p'):'file'===a?v+='-file':m&&(d?v=null:v='form-check-input'),n&&'undefined'==typeof l&&'undefined'==typeof r&&('danger'===n?r=!0:'success'===n&&(l=!0)),g.size&&b.test(g.size)&&(N('Please use the prop "bsSize" instead of the "size" to bootstrap\'s input sizing.'),s=g.size,delete g.size);var h=y(Q(t,r&&'is-invalid',l&&'is-valid',!!s&&'form-control-'+s,v),o);return('input'===f||'string'!=typeof i)&&(g.type=a),R.createElement(f,X({},g,{ref:u,className:h}))}}]),t}(R.Component);Qo.propTypes=Zo,Qo.defaultProps={type:'text'};var ea={tag:Z.oneOfType([Z.func,Z.string]),size:Z.string,className:Z.string,cssModule:Z.object},ta=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=e.size,n=J(e,['className','cssModule','tag','size']),l=y(Q(t,'input-group',s?'input-group-'+s:null),o);return R.createElement(a,X({},n,{className:l}))};ta.propTypes=ea,ta.defaultProps={tag:'div'};var oa={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object},aa=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'input-group-text'),o);return R.createElement(a,X({},s,{className:n}))};aa.propTypes=oa,aa.defaultProps={tag:'span'};var sa={tag:Z.oneOfType([Z.func,Z.string]),addonType:Z.oneOf(['prepend','append']).isRequired,children:Z.node,className:Z.string,cssModule:Z.object},na=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=e.addonType,n=e.children,l=J(e,['className','cssModule','tag','addonType','children']),r=y(Q(t,'input-group-'+s),o);return'string'==typeof n?R.createElement(a,X({},l,{className:r}),R.createElement(aa,{children:n})):R.createElement(a,X({},l,{className:r,children:n}))};na.propTypes=sa,na.defaultProps={tag:'div'};var la={tag:Z.oneOfType([Z.func,Z.string]),addonType:Z.oneOf(['prepend','append']).isRequired,children:Z.node,groupClassName:Z.string,groupAttributes:Z.object,className:Z.string,cssModule:Z.object},ra=function(e){N('The "InputGroupButton" component has been deprecated.\nPlease use component "InputGroupAddon".');var t=e.children,o=e.groupClassName,a=e.groupAttributes,s=J(e,['children','groupClassName','groupAttributes']);if('string'==typeof t){var n=s.cssModule,l=s.tag,r=s.addonType,i=J(s,['cssModule','tag','addonType']),d=X({},a,{cssModule:n,tag:l,addonType:r});return R.createElement(na,X({},d,{className:o}),R.createElement(Qe,X({},i,{children:t})))}return R.createElement(na,X({},e,{children:t}))};ra.propTypes=la;var ia={addonType:Z.oneOf(['prepend','append']).isRequired,children:Z.node},da=function(e){return R.createElement(We,e)};da.propTypes=ia;var ca=Z.oneOfType([Z.number,Z.string]),pa=Z.oneOfType([Z.string,Z.number,Z.shape({size:ca,push:T(ca,'Please use the prop "order"'),pull:T(ca,'Please use the prop "order"'),order:ca,offset:ca})]),ua={children:Z.node,hidden:Z.bool,check:Z.bool,size:Z.string,for:Z.string,tag:Z.string,className:Z.string,cssModule:Z.object,xs:pa,sm:pa,md:pa,lg:pa,xl:pa,widths:Z.array},ga=function(e,t,o){if(!0===o||''===o)return e?'col':'col-'+t;return'auto'===o?e?'col-auto':'col-'+t+'-auto':e?'col-'+o:'col-'+t+'-'+o},ma=function(e){var t=e.className,o=e.cssModule,a=e.hidden,s=e.widths,n=e.tag,l=e.check,r=e.size,i=e.for,d=J(e,['className','cssModule','hidden','widths','tag','check','size','for']),c=[];s.forEach(function(t,a){var s=e[t];if(delete d[t],s||''===s){var n,l=!a;if(Ee(s)){var r,p=l?'-':'-'+t+'-';n=ga(l,t,s.size),c.push(y(Q((r={},K(r,n,s.size||''===s.size),K(r,'order'+p+s.order,s.order||0===s.order),K(r,'offset'+p+s.offset,s.offset||0===s.offset),r))),o)}else n=ga(l,t,s),c.push(n)}});var p=y(Q(t,!!a&&'sr-only',!!l&&'form-check-label',!!r&&'col-form-label-'+r,c,!!c.length&&'col-form-label'),o);return R.createElement(n,X({htmlFor:i},d,{className:p}))};ma.propTypes=ua,ma.defaultProps={tag:'label',widths:['xs','sm','md','lg','xl']};var ba={body:Z.bool,bottom:Z.bool,children:Z.node,className:Z.string,cssModule:Z.object,heading:Z.bool,left:Z.bool,list:Z.bool,middle:Z.bool,object:Z.bool,right:Z.bool,tag:Z.oneOfType([Z.func,Z.string]),top:Z.bool},fa=function(e){var t,o=e.body,a=e.bottom,s=e.className,n=e.cssModule,l=e.heading,r=e.left,i=e.list,d=e.middle,c=e.object,p=e.right,u=e.tag,g=e.top,m=J(e,['body','bottom','className','cssModule','heading','left','list','middle','object','right','tag','top']);t=l?'h4':r||p?'a':c?'img':i?'ul':'div';var b=u||t,f=y(Q(s,{"media-body":o,"media-heading":l,"media-left":r,"media-right":p,"media-top":g,"media-bottom":a,"media-middle":d,"media-object":c,"media-list":i,media:!o&&!l&&!r&&!p&&!g&&!a&&!d&&!c&&!i}),n);return R.createElement(b,X({},m,{className:f}))};fa.propTypes=ba;var ya={children:Z.node,className:Z.string,cssModule:Z.object,size:Z.string,tag:Z.oneOfType([Z.func,Z.string])},va=function(e){var t=e.className,o=e.cssModule,a=e.size,s=e.tag,n=J(e,['className','cssModule','size','tag']),l=y(Q(t,'pagination',K({},'pagination-'+a,!!a)),o);return R.createElement(s,X({},n,{className:l}))};va.propTypes=ya,va.defaultProps={tag:'ul'};var ha={active:Z.bool,children:Z.node,className:Z.string,cssModule:Z.object,disabled:Z.bool,tag:Z.oneOfType([Z.func,Z.string])},Na=function(e){var t=e.active,o=e.className,a=e.cssModule,s=e.disabled,n=e.tag,l=J(e,['active','className','cssModule','disabled','tag']),r=y(Q(o,'page-item',{active:t,disabled:s}),a);return R.createElement(n,X({},l,{className:r}))};Na.propTypes=ha,Na.defaultProps={tag:'li'};var Ta={"aria-label":Z.string,children:Z.node,className:Z.string,cssModule:Z.object,next:Z.bool,previous:Z.bool,tag:Z.oneOfType([Z.func,Z.string])},ka=function(e){var t,o=e.className,a=e.cssModule,s=e.next,n=e.previous,l=e.tag,r=J(e,['className','cssModule','next','previous','tag']),i=y(Q(o,'page-link'),a);n?t='Previous':s&&(t='Next');var d,c=e['aria-label']||t;n?d='\xAB':s&&(d='\xBB');var p=e.children;return p&&Array.isArray(p)&&0===p.length&&(p=null),(n||s)&&(p=[R.createElement('span',{"aria-hidden":'true',key:'caret'},p||d),R.createElement('span',{className:'sr-only',key:'sr'},c)]),R.createElement(l,X({},r,{className:i,"aria-label":c}),p)};ka.propTypes=Ta,ka.defaultProps={tag:'a'};var Ea={tag:Z.oneOfType([Z.func,Z.string]),activeTab:Z.any,className:Z.string,cssModule:Z.object},Ma={activeTabId:Z.any},Oa=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={activeTab:o.props.activeTab},o}return V(t,e),W(t,[{key:'getChildContext',value:function(){return{activeTabId:this.state.activeTab}}},{key:'componentWillReceiveProps',value:function(e){this.state.activeTab!==e.activeTab&&this.setState({activeTab:e.activeTab})}},{key:'render',value:function(){var e=this.props,t=e.className,o=e.cssModule,a=e.tag,s=v(this.props,Object.keys(Ea)),n=y(Q('tab-content',t),o);return R.createElement(a,X({},s,{className:n}))}}]),t}(t.Component);Oa.propTypes=Ea,Oa.defaultProps={tag:'div'},Oa.childContextTypes=Ma;var xa={tag:Z.oneOfType([Z.func,Z.string]),className:Z.string,cssModule:Z.object,tabId:Z.any},Ca={activeTabId:Z.any};_.propTypes=xa,_.defaultProps={tag:'div'},_.contextTypes=Ca;var Pa={tag:Z.oneOfType([Z.func,Z.string]),fluid:Z.bool,className:Z.string,cssModule:Z.object},_a=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=e.fluid,n=J(e,['className','cssModule','tag','fluid']),l=y(Q(t,'jumbotron',!!s&&'jumbotron-fluid'),o);return R.createElement(a,X({},n,{className:l}))};_a.propTypes=Pa,_a.defaultProps={tag:'div'};var wa={children:Z.node,className:Z.string,closeClassName:Z.string,closeAriaLabel:Z.string,cssModule:Z.object,color:Z.string,isOpen:Z.bool,toggle:Z.func,tag:Z.oneOfType([Z.func,Z.string]),transition:Z.shape(M.propTypes)},ja={color:'success',isOpen:!0,tag:'div',closeAriaLabel:'Close',transition:X({},M.defaultProps,{unmountOnExit:!0})};w.propTypes=wa,w.defaultProps=ja;var Ia,Ra=X({},s.propTypes,{isOpen:Z.bool,children:Z.oneOfType([Z.arrayOf(Z.node),Z.node]),tag:Z.oneOfType([Z.func,Z.string]),className:Z.node,navbar:Z.bool,cssModule:Z.object}),Da=X({},s.defaultProps,{isOpen:!1,appear:!1,enter:!0,exit:!0,tag:'div',timeout:ue.Collapse}),Sa=(Ia={},K(Ia,me.ENTERING,'collapsing'),K(Ia,me.ENTERED,'collapse show'),K(Ia,me.EXITING,'collapsing'),K(Ia,me.EXITED,'collapse'),Ia),Aa=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={height:null},['onEntering','onEntered','onExit','onExiting','onExited'].forEach(function(e){o[e]=o[e].bind(o)}),o}return V(t,e),W(t,[{key:'onEntering',value:function(e,t){this.setState({height:I(e)}),this.props.onEntering(e,t)}},{key:'onEntered',value:function(e,t){this.setState({height:null}),this.props.onEntered(e,t)}},{key:'onExit',value:function(e){this.setState({height:I(e)}),this.props.onExit(e)}},{key:'onExiting',value:function(e){e.offsetHeight;this.setState({height:0}),this.props.onExiting(e)}},{key:'onExited',value:function(e){this.setState({height:null}),this.props.onExited(e)}},{key:'render',value:function(){var e=this.props,t=e.tag,o=e.isOpen,a=e.className,n=e.navbar,l=e.cssModule,r=e.children,i=J(e,['tag','isOpen','className','navbar','cssModule','children']),d=this.state.height,c=h(i,ge),p=v(i,ge);return R.createElement(s,X({},c,{in:o,onEntering:this.onEntering,onEntered:this.onEntered,onExit:this.onExit,onExiting:this.onExiting,onExited:this.onExited}),function(e){var o=j(e),s=y(Q(a,o,n&&'navbar-collapse'),l),i=null===d?null:{height:d};return R.createElement(t,X({},p,{style:X({},p.style,i),className:s}),r)})}}]),t}(t.Component);Aa.propTypes=Ra,Aa.defaultProps=Da;var za={tag:Z.oneOfType([Z.func,Z.string]),active:Z.bool,disabled:Z.bool,color:Z.string,action:Z.bool,className:Z.any,cssModule:Z.object},La=function(t){t.preventDefault()},qa=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=e.active,n=e.disabled,l=e.action,r=e.color,i=J(e,['className','cssModule','tag','active','disabled','action','color']),d=y(Q(t,!!s&&'active',!!n&&'disabled',!!l&&'list-group-item-action',!!r&&'list-group-item-'+r,'list-group-item'),o);return n&&(i.onClick=La),R.createElement(a,X({},i,{className:d}))};qa.propTypes=za,qa.defaultProps={tag:'li'};var Ha={tag:Z.oneOfType([Z.func,Z.string]),className:Z.any,cssModule:Z.object},Ba=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'list-group-item-heading'),o);return R.createElement(a,X({},s,{className:n}))};Ba.propTypes=Ha,Ba.defaultProps={tag:'h5'};var Ga={tag:Z.oneOfType([Z.func,Z.string]),className:Z.any,cssModule:Z.object},Ua=function(e){var t=e.className,o=e.cssModule,a=e.tag,s=J(e,['className','cssModule','tag']),n=y(Q(t,'list-group-item-text'),o);return R.createElement(a,X({},s,{className:n}))};Ua.propTypes=Ga,Ua.defaultProps={tag:'p'};var Fa=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={isOpen:!0},o.toggle=o.toggle.bind(o),o}return V(t,e),W(t,[{key:'toggle',value:function(){this.setState({isOpen:!this.state.isOpen})}},{key:'render',value:function(){return R.createElement(w,X({isOpen:this.state.isOpen,toggle:this.toggle},this.props))}}]),t}(t.Component),Wa=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={isOpen:!1},o.toggle=o.toggle.bind(o),o}return V(t,e),W(t,[{key:'toggle',value:function(){this.setState({isOpen:!this.state.isOpen})}},{key:'render',value:function(){return R.createElement(tt,X({isOpen:this.state.isOpen,toggle:this.toggle},this.props))}}]),t}(t.Component),Ka=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={isOpen:!1},o.toggle=o.toggle.bind(o),o}return V(t,e),W(t,[{key:'toggle',value:function(){this.setState({isOpen:!this.state.isOpen})}},{key:'render',value:function(){return R.createElement(We,X({isOpen:this.state.isOpen,toggle:this.toggle},this.props))}}]),t}(t.Component),Xa=function(e){function t(e){F(this,t);var o=Y(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return o.state={isOpen:!1},o.toggle=o.toggle.bind(o),o}return V(t,e),W(t,[{key:'toggle',value:function(){this.setState({isOpen:!this.state.isOpen})}},{key:'render',value:function(){return R.createElement(qo,X({isOpen:this.state.isOpen,toggle:this.toggle},this.props))}}]),t}(t.Component);e.Alert=w,e.Container=Ne,e.Row=ke,e.Col=Pe,e.Navbar=Re,e.NavbarBrand=Se,e.NavbarToggler=ze,e.Nav=He,e.NavItem=Ge,e.NavDropdown=function(e){return N('The "NavDropdown" component has been deprecated.\nPlease use component "Dropdown" with nav prop.'),R.createElement(We,X({nav:!0},e))},e.NavLink=Xe,e.Breadcrumb=Je,e.BreadcrumbItem=$e,e.Button=Qe,e.ButtonDropdown=tt,e.ButtonGroup=at,e.ButtonToolbar=nt,e.Dropdown=We,e.DropdownItem=it,e.DropdownMenu=gt,e.DropdownToggle=ft,e.Fade=M,e.Badge=Nt,e.Card=kt,e.CardLink=It,e.CardGroup=Mt,e.CardDeck=xt,e.CardColumns=Pt,e.CardBody=wt,e.CardBlock=function(e){return N('The "CardBlock" component has been deprecated.\nPlease use component "CardBody".'),R.createElement(wt,e)},e.CardFooter=Dt,e.CardHeader=At,e.CardImg=Lt,e.CardImgOverlay=Ht,e.Carousel=Gt,e.UncontrolledCarousel=Xt,e.CarouselControl=Ut,e.CarouselItem=Bt,e.CarouselIndicators=Ft,e.CarouselCaption=Wt,e.CardSubtitle=Jt,e.CardText=$t,e.CardTitle=Qt,e.Popover=lo,e.PopoverContent=function(e){return N('The "PopoverContent" component has been deprecated.\nPlease use component "PopoverBody".'),R.createElement(po,e)},e.PopoverBody=po,e.PopoverTitle=function(e){return N('The "PopoverTitle" component has been deprecated.\nPlease use component "PopoverHeader".'),R.createElement(io,e)},e.PopoverHeader=io,e.Progress=Eo,e.Modal=wo,e.ModalHeader=Io,e.ModalBody=Do,e.ModalFooter=Ao,e.PopperContent=oo,e.PopperTargetHelper=ao,e.Tooltip=qo,e.Table=Bo,e.ListGroup=Uo,e.Form=Wo,e.FormFeedback=Xo,e.FormGroup=Jo,e.FormText=$o,e.Input=Qo,e.InputGroup=ta,e.InputGroupAddon=na,e.InputGroupButton=ra,e.InputGroupButtonDropdown=da,e.InputGroupText=aa,e.Label=ma,e.Media=fa,e.Pagination=va,e.PaginationItem=Na,e.PaginationLink=ka,e.TabContent=Oa,e.TabPane=_,e.Jumbotron=_a,e.Collapse=Aa,e.ListGroupItem=qa,e.ListGroupItemText=Ua,e.ListGroupItemHeading=Ba,e.UncontrolledAlert=Fa,e.UncontrolledButtonDropdown=Wa,e.UncontrolledDropdown=Ka,e.UncontrolledNavDropdown=function(e){return N('The "UncontrolledNavDropdown" component has been deprecated.\nPlease use component "UncontrolledDropdown" with nav prop.'),R.createElement(Ka,X({nav:!0},e))},e.UncontrolledTooltip=Xa,e.Util=ve,Object.defineProperty(e,'__esModule',{value:!0})});
//# sourceMappingURL=reactstrap.min.js.map
|
ajax/libs/6to5/1.13.11/browser-polyfill.js | drewfreyling/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(require,module,exports){(function(global){var ensureSymbol=function(key){Symbol[key]=Symbol[key]||Symbol()};var ensureProto=function(Constructor,key,val){var proto=Constructor.prototype;proto[key]=proto[key]||val};if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("./transformation/transformers/es6-generators/runtime");ensureSymbol("referenceGet");ensureSymbol("referenceSet");ensureSymbol("referenceDelete");ensureProto(Function,Symbol.referenceGet,function(){return this});ensureProto(Map,Symbol.referenceGet,Map.prototype.get);ensureProto(Map,Symbol.referenceSet,Map.prototype.set);ensureProto(Map,Symbol.referenceDelete,Map.prototype.delete);if(global.WeakMap){ensureProto(WeakMap,Symbol.referenceGet,WeakMap.prototype.get);ensureProto(WeakMap,Symbol.referenceSet,WeakMap.prototype.set);ensureProto(WeakMap,Symbol.referenceDelete,WeakMap.prototype.delete)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transformers/es6-generators/runtime":2,"es6-shim":4,"es6-symbol/implement":5}],2:[function(require,module,exports){(function(global){var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var runtime=global.regeneratorRuntime=exports;var hasOwn=Object.prototype.hasOwnProperty;var wrap=runtime.wrap=function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])};var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};var GF=function GeneratorFunction(){};var GFp=function GeneratorFunctionPrototype(){};var Gp=GFp.prototype=Generator.prototype;(GFp.constructor=GF).prototype=Gp.constructor=GFp;var GFName="GeneratorFunction";if(GF.name!==GFName)GF.name=GFName;if(GF.name!==GFName)throw new Error(GFName+" renamed?");runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GF.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var info;var value;try{info=this(arg);value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;var info;if(delegate){try{info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;var thrown;if(record.type==="throw"){thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],3:[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")}},{}],4:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}Object.setPrototypeOf(Sub,C);Sub.prototype=Object.create(C.prototype,{constructor:{value:C}});return f(Sub)}catch(e){return false}};var arePropertyDescriptorsSupported=function(){try{Object.defineProperty({},"x",{});return true}catch(e){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");var globals=getGlobal();var global_isFinite=globals.isFinite;var supportsDescriptors=!!Object.defineProperty&&arePropertyDescriptorsSupported();var startsWithIsCompliant=startsWithRejectsRegex();var _slice=Array.prototype.slice;var _indexOf=String.prototype.indexOf;var _toString=Object.prototype.toString;var _hasOwnProperty=Object.prototype.hasOwnProperty;var ArrayIterator;var defineProperty=function(object,name,value,force){if(!force&&name in object){return}if(supportsDescriptors){Object.defineProperty(object,name,{configurable:true,enumerable:false,writable:true,value:value})}else{object[name]=value}};var defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};var create=Object.create||function(prototype,properties){function Type(){}Type.prototype=prototype;var object=new Type;if(typeof properties!=="undefined"){defineProperties(object,properties)}return object};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(globals.Set&&typeof(new globals.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var addIterator=function(prototype,impl){if(!impl){impl=function iterator(){return this}}var o={};o[$iterator$]=impl;defineProperties(prototype,o);if(!prototype[$iterator$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};var isArguments=function isArguments(value){var str=_toString.call(value);var result=str==="[object Arguments]";if(!result){result=str!=="[object Array]"&&value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&_toString.call(value.callee)==="[object Function]"}return result};var emulateES6construct=function(o){if(!ES.TypeIsObject(o)){throw new TypeError("bad object")}if(!o._es6construct){if(o.constructor&&ES.IsCallable(o.constructor["@@create"])){o=o.constructor["@@create"](o)}defineProperties(o,{_es6construct:true})}return o};var ES={CheckObjectCoercible:function(x,optMessage){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="function"&&_toString.call(x)==="[object Function]"},ToInt32:function(x){return x>>0},ToUint32:function(x){return x>>>0},ToInteger:function(value){var number=+value;if(Number.isNaN(number)){return 0}if(number===0||!Number.isFinite(number)){return number}return(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){return a===b||Number.isNaN(a)&&Number.isNaN(b)},IsIterable:function(o){return ES.TypeIsObject(o)&&(typeof o[$iterator$]!=="undefined"||isArguments(o))},GetIterator:function(o){if(isArguments(o)){return new ArrayIterator(o,"value")}var itFn=o[$iterator$];if(!ES.IsCallable(itFn)){throw new TypeError("value is not an iterable")}var it=itFn.call(o);if(!ES.TypeIsObject(it)){throw new TypeError("bad iterator")}return it},IteratorNext:function(it){var result=arguments.length>1?it.next(arguments[1]):it.next();if(!ES.TypeIsObject(result)){throw new TypeError("bad iterator")}return result},Construct:function(C,args){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.5){return w+1}return w%2?w+1:w}function packIEEE754(v,ebits,fbits){var bias=(1<<ebits-1)-1,s,e,f,i,bits,str,bytes;if(v!==v){e=(1<<ebits)-1;f=Math.pow(2,fbits-1);s=0}else if(v===Infinity||v===-Infinity){e=(1<<ebits)-1;f=0;s=v<0?1:0}else if(v===0){e=0;f=0;s=1/v===-Infinity?1:0}else{s=v<0;v=Math.abs(v);if(v>=Math.pow(2,1-bias)){e=Math.min(Math.floor(Math.log(v)/Math.LN2),1023);f=roundToEven(v/Math.pow(2,e)*Math.pow(2,fbits));if(f/Math.pow(2,fbits)>=2){e=e+1;f=1}if(e>bias){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}bits=[];for(i=fbits;i;i-=1){bits.push(f%2?1:0);f=Math.floor(f/2)}for(i=ebits;i;i-=1){bits.push(e%2?1:0);e=Math.floor(e/2)}bits.push(s?1:0);bits.reverse();str=bits.join("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){var bits=[],i,j,b,str,bias,s,e,f;for(i=bytes.length;i;i-=1){b=bytes[i-1];for(j=8;j;j-=1){bits.push(b%2?1:0);b=b>>1}}bits.reverse();str=bits.join("");bias=(1<<ebits-1)-1;s=parseInt(str.slice(0,1),2)?-1:1;e=parseInt(str.slice(1,1+ebits),2);f=parseInt(str.slice(1+ebits),2);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){return s*Math.pow(2,-(bias-1))*(f/Math.pow(2,fbits))}else{return s<0?-0:0}}function unpackFloat64(b){return unpackIEEE754(b,11,52)}function packFloat64(v){return packIEEE754(v,11,52)}function unpackFloat32(b){return unpackIEEE754(b,8,23)}function packFloat32(v){return packIEEE754(v,8,23)}var conversions={toFloat32:function(num){return unpackFloat32(packFloat32(num))}};if(typeof Float32Array!=="undefined"){var float32array=new Float32Array(1);conversions.toFloat32=function(num){float32array[0]=num;return float32array[0]}}return conversions}();defineProperties(String,{fromCodePoint:function(_){var points=_slice.call(arguments,0,arguments.length);var result=[];var next;for(var i=0,length=points.length;i<length;i++){next=Number(points[i]);if(!ES.SameValue(next,ES.ToInteger(next))||next<0||next>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join("")},raw:function(callSite){var substitutions=_slice.call(arguments,1,arguments.length);var cooked=ES.ToObject(callSite,"bad callSite");var rawValue=cooked.raw;var raw=ES.ToObject(rawValue,"bad raw value");var len=Object.keys(raw).length;var literalsegments=ES.ToLength(len);if(literalsegments===0){return""}var stringElements=[];var nextIndex=0;var nextKey,next,nextSeg,nextSub;while(nextIndex<literalsegments){nextKey=String(nextIndex);next=raw[nextKey];nextSeg=String(next);stringElements.push(nextSeg);if(nextIndex+1>=literalsegments){break}next=substitutions[nextKey];if(typeof next==="undefined"){break}nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={repeat:function(){var repeat=function(s,times){if(times<1){return""}if(times%2){return repeat(s,times-1)+s}var half=repeat(s,times/2);return half+half};return function(times){var thisStr=String(ES.CheckObjectCoercible(this));times=ES.ToInteger(times);if(times<0||times===Infinity){throw new RangeError("Invalid String#repeat value")}return repeat(thisStr,times)}}(),startsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "startsWith" with a regex')}searchStr=String(searchStr);var startArg=arguments.length>1?arguments[1]:void 0;var start=Math.max(ES.ToInteger(startArg),0);return thisStr.slice(start,start+searchStr.length)===searchStr},endsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "endsWith" with a regex')}searchStr=String(searchStr);var thisLen=thisStr.length;var posArg=arguments.length>1?arguments[1]:void 0;var pos=typeof posArg==="undefined"?thisLen:ES.ToInteger(posArg);var end=Math.min(Math.max(pos,0),thisLen);return thisStr.slice(end-searchStr.length,end)===searchStr},contains:function(searchString){var position=arguments.length>1?arguments[1]:void 0;return _indexOf.call(this,searchString,position)!==-1},codePointAt:function(pos){var thisStr=String(ES.CheckObjectCoercible(this));var position=ES.ToInteger(pos);var length=thisStr.length;if(position<0||position>=length){return}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="
".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n\f\r "," \u2028","\u2029"].join("");var trimRegexp=new RegExp("(^["+ws+"]+)|(["+ws+"]+$)","g");defineProperties(String.prototype,{trim:function(){if(typeof this==="undefined"||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(trimRegexp,"")}})}var StringIterator=function(s){this._s=String(ES.CheckObjectCoercible(s));this._i=0};StringIterator.prototype.next=function(){var s=this._s,i=this._i;if(typeof s==="undefined"||i>=s.length){this._s=void 0;return{value:void 0,done:true}}var first=s.charCodeAt(i),second,len;if(first<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?1:2}this._i=i+len;return{value:s.substr(i,len),done:false}};addIterator(StringIterator.prototype);addIterator(String.prototype,function(){return new StringIterator(this)});if(!startsWithIsCompliant){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}var ArrayShims={from:function(iterable){var mapFn=arguments.length>1?arguments[1]:void 0;var list=ES.ToObject(iterable,"bad iterable");if(typeof mapFn!=="undefined"&&!ES.IsCallable(mapFn)){throw new TypeError("Array.from: when provided, the second argument must be a function")}var hasThisArg=arguments.length>2;var thisArg=hasThisArg?arguments[2]:void 0;var usingIterator=ES.IsIterable(list);var length;var result,i,value;if(usingIterator){i=0;result=ES.IsCallable(this)?Object(new this):[];var it=usingIterator?ES.GetIterator(list):null;var iterationValue;do{iterationValue=ES.IteratorNext(it);if(!iterationValue.done){value=iterationValue.value;if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}i+=1}}while(!iterationValue.done);length=i}else{length=ES.ToLength(list.length);result=ES.IsCallable(this)?Object(new this(length)):new Array(length);for(i=0;i<length;++i){value=list[i];if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}}}result.length=length;return result},of:function(){return Array.from(arguments)}};defineProperties(Array,ArrayShims);var arrayFromSwallowsNegativeLengths=function(){try{return Array.from({length:-1}).length===0}catch(e){return false}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}ArrayIterator=function(array,kind){this.i=0;this.array=array;this.kind=kind};defineProperties(ArrayIterator.prototype,{next:function(){var i=this.i,array=this.array;if(!(this instanceof ArrayIterator)){throw new TypeError("Not an ArrayIterator")}if(typeof array!=="undefined"){var len=ES.ToLength(array.length);for(;i<len;i++){var kind=this.kind;var retval;if(kind==="key"){retval=i}else if(kind==="value"){retval=array[i]}else if(kind==="entry"){retval=[i,array[i]]}this.i=i+1;return{value:retval,done:false}}}this.array=void 0;return{value:void 0,done:true}}});addIterator(ArrayIterator.prototype);var ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[2];var o=ES.ToObject(this);var len=ES.ToLength(o.length);target=ES.ToInteger(target);start=ES.ToInteger(start);var to=target<0?Math.max(len+target,0):Math.min(target,len);var from=start<0?Math.max(len+start,0):Math.min(start,len);end=typeof end==="undefined"?len:ES.ToInteger(end);var fin=end<0?Math.max(len+end,0):Math.min(end,len);var count=Math.min(fin-from,len-to);var direction=1;if(from<to&&to<from+count){direction=-1;from+=count-1;to+=count-1}while(count>0){if(_hasOwnProperty.call(o,from)){o[to]=o[from]}else{delete o[from]}from+=direction;to+=direction;count-=1}return o},fill:function(value){var start=arguments.length>1?arguments[1]:void 0;var end=arguments.length>2?arguments[2]:void 0;var O=ES.ToObject(this);var len=ES.ToLength(O.length);start=ES.ToInteger(typeof start==="undefined"?0:start);end=ES.ToInteger(typeof end==="undefined"?len:end);var relativeStart=start<0?Math.max(len+start,0):Math.min(start,len);var relativeEnd=end<0?len+end:end;for(var i=relativeStart;i<len&&i<relativeEnd;++i){O[i]=value}return O},find:function find(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#find: predicate must be a function")}var thisArg=arguments[1];for(var i=0,value;i<length;i++){value=list[i];if(predicate.call(thisArg,value,i,list)){return value}}return},findIndex:function findIndex(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#findIndex: predicate must be a function")}var thisArg=arguments[1];for(var i=0;i<length;i++){if(predicate.call(thisArg,list[i],i,list)){return i}}return-1},keys:function(){return new ArrayIterator(this,"key")},values:function(){return new ArrayIterator(this,"value")},entries:function(){return new ArrayIterator(this,"entry")}};if(Array.prototype.keys&&!ES.IsCallable([1].keys().next)){delete Array.prototype.keys}if(Array.prototype.entries&&!ES.IsCallable([1].entries().next)){delete Array.prototype.entries}if(Array.prototype.keys&&Array.prototype.entries&&!Array.prototype.values&&Array.prototype[$iterator$]){defineProperties(Array.prototype,{values:Array.prototype[$iterator$]})}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});if(Object.getPrototypeOf){addIterator(Object.getPrototypeOf([].values()))}var maxSafeInteger=Math.pow(2,53)-1;defineProperties(Number,{MAX_SAFE_INTEGER:maxSafeInteger,MIN_SAFE_INTEGER:-maxSafeInteger,EPSILON:2.220446049250313e-16,parseInt:globals.parseInt,parseFloat:globals.parseFloat,isFinite:function(value){return typeof value==="number"&&global_isFinite(value)},isInteger:function(value){return Number.isFinite(value)&&ES.ToInteger(value)===value},isSafeInteger:function(value){return Number.isInteger(value)&&Math.abs(value)<=Number.MAX_SAFE_INTEGER},isNaN:function(value){return value!==value}});if(![,1].find(function(item,idx){return idx===0})){defineProperty(Array.prototype,"find",ArrayPrototypeShims.find,true)}if([,1].findIndex(function(item,idx){return idx===0})!==0){defineProperty(Array.prototype,"findIndex",ArrayPrototypeShims.findIndex,true)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof pd==="undefined"&&proto!==null){pd=Object.getOwnPropertyDescriptor(proto,name);proto=Object.getPrototypeOf(proto)}return pd},getPropertyNames:function(subject){var result=Object.getOwnPropertyNames(subject);var proto=Object.getPrototypeOf(subject);var addProperty=function(property){if(result.indexOf(property)===-1){result.push(property)}};while(proto!==null){Object.getOwnPropertyNames(proto).forEach(addProperty);proto=Object.getPrototypeOf(proto)}return result}});defineProperties(Object,{assign:function(target,source){if(!ES.TypeIsObject(target)){throw new TypeError("target must be an object")}return Array.prototype.reduce.call(arguments,function(target,source){return Object.keys(Object(source)).reduce(function(target,key){target[key]=source[key];return target},target)})},is:function(a,b){return ES.SameValue(a,b)},setPrototypeOf:function(Object,magic){var set;var checkArgs=function(O,proto){if(!ES.TypeIsObject(O)){throw new TypeError("cannot set prototype on a non-object")}if(!(proto===null||ES.TypeIsObject(proto))){throw new TypeError("can only set prototype to an object or null"+proto)}};var setPrototypeOf=function(O,proto){checkArgs(O,proto);set.call(O,proto);return O};try{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}if(Object.setPrototypeOf&&Object.getPrototypeOf&&Object.getPrototypeOf(Object.setPrototypeOf({},null))!==null&&Object.getPrototypeOf(Object.create(null))===null){(function(){var FAKENULL=Object.create(null);var gpo=Object.getPrototypeOf,spo=Object.setPrototypeOf;Object.getPrototypeOf=function(o){var result=gpo(o);return result===FAKENULL?null:result};Object.setPrototypeOf=function(o,p){if(p===null){p=FAKENULL}return spo(o,p)};Object.setPrototypeOf.polyfill=false})()}try{Object.keys("foo")}catch(e){var originalObjectKeys=Object.keys;Object.keys=function(obj){return originalObjectKeys(ES.ToObject(obj))}}var MathShims={acosh:function(value){value=Number(value);if(Number.isNaN(value)||value<1){return NaN}if(value===1){return 0}if(value===Infinity){return value}return Math.log(value+Math.sqrt(value*value-1))},asinh:function(value){value=Number(value);if(value===0||!global_isFinite(value)){return value}return value<0?-Math.asinh(-value):Math.log(value+Math.sqrt(value*value+1))},atanh:function(value){value=Number(value);if(Number.isNaN(value)||value<-1||value>1){return NaN}if(value===-1){return-Infinity}if(value===1){return Infinity}if(value===0){return value}return.5*Math.log((1+value)/(1-value))},cbrt:function(value){value=Number(value);if(value===0){return value}var negate=value<0,result;if(negate){value=-value}result=Math.pow(value,1/3);return negate?-result:result},clz32:function(value){value=Number(value);var number=ES.ToUint32(value);if(number===0){return 32}return 32-number.toString(2).length},cosh:function(value){value=Number(value);if(value===0){return 1}if(Number.isNaN(value)){return NaN}if(!global_isFinite(value)){return Infinity}if(value<0){value=-value}if(value>21){return Math.exp(value)/2}return(Math.exp(value)+Math.exp(-value))/2},expm1:function(value){value=Number(value);if(value===-Infinity){return-1}if(!global_isFinite(value)||value===0){return value}return Math.exp(value)-1},hypot:function(x,y){var anyNaN=false;var allZero=true;var anyInfinity=false;var numbers=[];Array.prototype.every.call(arguments,function(arg){var num=Number(arg);if(Number.isNaN(num)){anyNaN=true}else if(num===Infinity||num===-Infinity){anyInfinity=true}else if(num!==0){allZero=false}if(anyInfinity){return false}else if(!anyNaN){numbers.push(Math.abs(num))}return true});if(anyInfinity){return Infinity}if(anyNaN){return NaN}if(allZero){return 0}numbers.sort(function(a,b){return b-a});var largest=numbers[0];var divided=numbers.map(function(number){return number/largest});var sum=divided.reduce(function(sum,number){return sum+=number*number},0);return largest*Math.sqrt(sum)},log2:function(value){return Math.log(value)*Math.LOG2E},log10:function(value){return Math.log(value)*Math.LOG10E},log1p:function(value){value=Number(value);if(value<-1||Number.isNaN(value)){return NaN}if(value===0||value===Infinity){return value}if(value===-1){return-Infinity}var result=0;var n=50;if(value<0||value>1){return Math.log(1+value)}for(var i=1;i<n;i++){if(i%2===0){result-=Math.pow(value,i)/i}else{result+=Math.pow(value,i)/i}}return result},sign:function(value){var number=+value;if(number===0){return number}if(Number.isNaN(number)){return number}return number<0?-1:1},sinh:function(value){value=Number(value);if(!global_isFinite(value)||value===0){return value}return(Math.exp(value)-Math.exp(-value))/2},tanh:function(value){value=Number(value);if(Number.isNaN(value)||value===0){return value}if(value===Infinity){return 1}if(value===-Infinity){return-1}return(Math.exp(value)-Math.exp(-value))/(Math.exp(value)+Math.exp(-value))},trunc:function(value){var number=Number(value);return number<0?-Math.floor(-number):Math.floor(number)},imul:function(x,y){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0},fround:function(x){if(x===0||x===Infinity||x===-Infinity||Number.isNaN(x)){return x}var num=Number(x);return numberConversion.toFloat32(num)}};defineProperties(Math,MathShims);if(Math.imul(4294967295,5)!==-5){Math.imul=MathShims.imul
}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};var PromiseCapability=function(C){if(!ES.IsCallable(C)){throw new TypeError("bad promise constructor")}var capability=this;var resolver=function(resolve,reject){capability.resolve=resolve;capability.reject=reject};capability.promise=ES.Construct(C,[resolver]);if(!capability.promise._es6construct){throw new TypeError("bad promise constructor")}if(!(ES.IsCallable(capability.resolve)&&ES.IsCallable(capability.reject))){throw new TypeError("bad promise constructor")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){var timeouts=[];var messageName="zero-timeout-message";var setZeroTimeout=function(fn){timeouts.push(fn);window.postMessage(messageName,"*")};var handleMessage=function(event){if(event.source==window&&event.data==messageName){event.stopPropagation();if(timeouts.length===0){return}var fn=timeouts.shift();fn()}};window.addEventListener("message",handleMessage,true);return setZeroTimeout}}var makePromiseAsap=function(){var P=globals.Promise;return P&&P.resolve&&function(task){return P.resolve().then(task)}};var enqueue=ES.IsCallable(globals.setImmediate)?globals.setImmediate.bind(globals):typeof process==="object"&&process.nextTick?process.nextTick:makePromiseAsap()||(ES.IsCallable(makeZeroTimeout)?makeZeroTimeout():function(task){setTimeout(task,0)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){var handler=reaction.handler;var capability=reaction.capability;var resolve=capability.resolve;var reject=capability.reject;try{var result=handler(x);if(result===capability.promise){throw new TypeError("self resolution")}var updateResult=updatePromiseFromPotentialThenable(result,capability);if(!updateResult){resolve(result)}}catch(e){reject(e)}})})};var updatePromiseFromPotentialThenable=function(x,capability){if(!ES.TypeIsObject(x)){return false}var resolve=capability.resolve;var reject=capability.reject;try{var then=x.then;if(!ES.IsCallable(then)){return false}then.call(x,resolve,reject)}catch(e){reject(e)}return true};var promiseResolutionHandler=function(promise,onFulfilled,onRejected){return function(x){if(x===promise){return onRejected(new TypeError("self resolution"))}var C=promise._promiseConstructor;var capability=new PromiseCapability(C);var updateResult=updatePromiseFromPotentialThenable(x,capability);if(updateResult){return capability.promise.then(onFulfilled,onRejected)}else{return onFulfilled(x)}}};Promise=function(resolver){var promise=this;promise=emulateES6construct(promise);if(!promise._promiseConstructor){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}if(!ES.IsCallable(resolver)){throw new TypeError("not a valid resolver")}promise._status="unresolved";promise._resolveReactions=[];promise._rejectReactions=[];var resolve=function(resolution){if(promise._status!=="unresolved"){return}var reactions=promise._resolveReactions;promise._result=resolution;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-resolution";triggerPromiseReactions(reactions,resolution)};var reject=function(reason){if(promise._status!=="unresolved"){return}var reactions=promise._rejectReactions;promise._result=reason;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-rejection";triggerPromiseReactions(reactions,reason)};try{resolver(resolve,reject)}catch(e){reject(e)}return promise};Promise$prototype=Promise.prototype;defineProperties(Promise,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Promise$prototype;obj=obj||create(prototype);defineProperties(obj,{_status:void 0,_result:void 0,_resolveReactions:void 0,_rejectReactions:void 0,_promiseConstructor:void 0});obj._promiseConstructor=constructor;return obj}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};Promise.all=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);var values=[],remaining={count:1};for(var index=0;;index++){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);var resolveElement=_promiseAllResolver(index,values,capability,remaining);remaining.count++;nextPromise.then(resolveElement,capability.reject)}if(--remaining.count===0){resolve(values)}}catch(e){reject(e)}return capability.promise};Promise.race=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);nextPromise.then(resolve,reject)}}catch(e){reject(e)}return capability.promise};Promise.reject=function(reason){var C=this;var capability=new PromiseCapability(C);var reject=capability.reject;reject(reason);return capability.promise};Promise.resolve=function(v){var C=this;if(ES.IsPromise(v)){var constructor=v._promiseConstructor;if(constructor===C){return v}}var capability=new PromiseCapability(C);var resolve=capability.resolve;resolve(v);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}var C=this.constructor;var capability=new PromiseCapability(C);if(!ES.IsCallable(onRejected)){onRejected=function(e){throw e}}if(!ES.IsCallable(onFulfilled)){onFulfilled=function(x){return x}}var resolutionHandler=promiseResolutionHandler(promise,onFulfilled,onRejected);var resolveReaction={capability:capability,handler:resolutionHandler};var rejectReaction={capability:capability,handler:onRejected};switch(promise._status){case"unresolved":promise._resolveReactions.push(resolveReaction);promise._rejectReactions.push(rejectReaction);break;case"has-resolution":triggerPromiseReactions([resolveReaction],promise._result);break;case"has-rejection":triggerPromiseReactions([rejectReaction],promise._result);break;default:throw new TypeError("unexpected")}return capability.promise};return Promise}();defineProperties(globals,{Promise:PromiseShim});var promiseSupportsSubclassing=supportsSubclassing(globals.Promise,function(S){return S.resolve(42)instanceof S});var promiseIgnoresNonFunctionThenCallbacks=function(){try{globals.Promise.reject(42).then(null,5).then(null,function(){});return true}catch(ex){return false}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}var testOrder=function(a){var b=Object.keys(a.reduce(function(o,k){o[k]=true;return o},{}));return a.join(":")===b.join(":")};var preservesInsertionOrder=testOrder(["z","a","bb"]);var preservesNumericInsertionOrder=testOrder(["z",1,"a","3",2]);if(supportsDescriptors){var fastkey=function fastkey(key){if(!preservesInsertionOrder){return null}var type=typeof key;if(type==="string"){return"$"+key}else if(type==="number"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){return Object.create?Object.create(null):{}};var collectionShims={Map:function(){var empty={};function MapEntry(key,value){this.key=key;this.value=value;this.next=null;this.prev=null}MapEntry.prototype.isRemoved=function(){return this.key===empty};function MapIterator(map,kind){this.head=map._head;this.i=this.head;this.kind=kind}MapIterator.prototype={next:function(){var i=this.i,kind=this.kind,head=this.head,result;if(typeof this.i==="undefined"){return{value:void 0,done:true}}while(i.isRemoved()&&i!==head){i=i.prev}while(i.next!==head){i=i.next;if(!i.isRemoved()){if(kind==="key"){result=i.key}else if(kind==="value"){result=i.value}else{result=[i.key,i.value]}this.i=i;return{value:result,done:false}}}this.i=void 0;return{value:void 0,done:true}}};addIterator(MapIterator.prototype);function Map(iterable){var map=this;if(!ES.TypeIsObject(map)){throw new TypeError("Map does not accept arguments when called as a function")}map=emulateES6construct(map);if(!map._es6map){throw new TypeError("bad map")}var head=new MapEntry(null,null);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=map.set;if(!ES.IsCallable(adder)){throw new TypeError("bad map")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;if(!ES.TypeIsObject(nextItem)){throw new TypeError("expected iterable of pairs")}adder.call(map,nextItem[0],nextItem[1])}}return map}var Map$prototype=Map.prototype;defineProperties(Map,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Map$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6map:true});return obj}});Object.defineProperty(Map.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size}});defineProperties(Map.prototype,{get:function(key){var fkey=fastkey(key);if(fkey!==null){var entry=this._storage[fkey];if(entry){return entry.value}else{return}}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return i.value}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){return typeof this._storage[fkey]!=="undefined"}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return true}}return false},set:function(key,value){var head=this._head,i=head,entry;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]!=="undefined"){this._storage[fkey].value=value;return this}else{entry=this._storage[fkey]=new MapEntry(key,value);i=head.prev}}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.value=value;return this}}entry=entry||new MapEntry(key,value);if(ES.SameValue(-0,key)){entry.key=+0}entry.next=this._head;entry.prev=this._head.prev;entry.prev.next=entry;entry.next.prev=entry;this._size+=1;return this},"delete":function(key){var head=this._head,i=head;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.key=i.value=empty;i.prev.next=i.next;i.next.prev=i.prev;this._size-=1;return true}}return false},clear:function(){this._size=0;this._storage=emptyObject();var head=this._head,i=head,p=i.next;while((i=p)!==head){i.key=i.value=empty;p=i.next;i.next=i.prev=head}head.next=head.prev=head},keys:function(){return new MapIterator(this,"key")},values:function(){return new MapIterator(this,"value")},entries:function(){return new MapIterator(this,"key+value")},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var it=this.entries();for(var entry=it.next();!entry.done;entry=it.next()){callback.call(context,entry.value[1],entry.value[0],this)}}});addIterator(Map.prototype,function(){return this.entries()});return Map}(),Set:function(){var SetShim=function Set(iterable){var set=this;if(!ES.TypeIsObject(set)){throw new TypeError("Set does not accept arguments when called as a function")}set=emulateES6construct(set);if(!set._es6set){throw new TypeError("bad set")}defineProperties(set,{"[[SetData]]":null,_storage:emptyObject()});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=set.add;if(!ES.IsCallable(adder)){throw new TypeError("bad set")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;adder.call(set,nextItem)}}return set};var Set$prototype=SetShim.prototype;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){if(k.charCodeAt(0)===36){k=k.slice(1)}else if(k.charAt(0)==="n"){k=+k.slice(1)}else{k=+k}m.set(k,k)});set._storage=null}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){throw new TypeError("size method called on incompatible Set")}ensureMap(this);return this["[[SetData]]"].size}});defineProperties(SetShim.prototype,{has:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){return!!this._storage[fkey]}ensureMap(this);return this["[[SetData]]"].has(key)},add:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){this._storage[fkey]=true;return this}ensureMap(this);this["[[SetData]]"].set(key,key);return this},"delete":function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){var hasFKey=_hasOwnProperty.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this["[[SetData]]"]["delete"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return this["[[SetData]]"].clear()},keys:function(){ensureMap(this);return this["[[SetData]]"].keys()},values:function(){ensureMap(this);return this["[[SetData]]"].values()},entries:function(){ensureMap(this);return this["[[SetData]]"].entries()},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var entireSet=this;ensureMap(this);this["[[SetData]]"].forEach(function(value,key){callback.call(context,key,key,entireSet)})}});addIterator(SetShim.prototype,function(){return this.values()});return SetShim}()};defineProperties(globals,collectionShims);if(globals.Map||globals.Set){if(typeof globals.Map.prototype.clear!=="function"||(new globals.Set).size!==0||(new globals.Map).size!==0||typeof globals.Map.prototype.keys!=="function"||typeof globals.Set.prototype.keys!=="function"||typeof globals.Map.prototype.forEach!=="function"||typeof globals.Set.prototype.forEach!=="function"||isCallableWithoutNew(globals.Map)||isCallableWithoutNew(globals.Set)||!supportsSubclassing(globals.Map,function(M){var m=new M([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:3}],5:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":6,"./polyfill":21,"es5-ext/global":8}],6:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],7:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":9,"es5-ext/object/is-callable":12,"es5-ext/object/normalize-options":16,"es5-ext/string/#/contains":18}],8:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],9:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":10,"./shim":11}],10:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],11:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":13,"../valid-value":17}],12:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],13:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":14,"./shim":15}],14:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],15:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],16:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":9}],17:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],18:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":19,"./shim":20}],19:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],20:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],21:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:7}]},{},[1]); |
src/components/editor/editor-edges.js | szymonkaliski/SDF-UI | import React, { Component } from 'react';
import autobind from 'react-autobind';
import classNames from 'classnames';
import enhanceWithClickOutside from 'react-click-outside';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import nodeSpecs from '../../engine/nodes';
import {
deleteEdge
} from '../../actions/graph';
import './editor-edges.css';
const prop = (key) => (obj) => obj[key];
class EditorEdges extends Component {
constructor() {
super();
this.state = { selectedId: undefined };
autobind(this);
}
componentDidMount() {
window.addEventListener('keydown', this.onKeyDown);
}
componentWillUnmount() {
window.removeEventListener('keydown', this.onKeyDown);
}
onClickEdge(id) {
this.setState({ selectedId: id });
}
handleClickOutside() {
this.setState({ selectedId: undefined });
}
onKeyDown(e) {
const { key, target } = e;
const { selectedId } = this.state;
if (selectedId && key === 'Backspace' && target.localName === 'body') {
this.props.deleteEdge(selectedId);
this.setState({ selectedId: undefined });
}
}
render() {
const { selectedId } = this.state;
const { width, height, edges, nodes } = this.props;
return <svg className='edges' width={ width } height={ height }>
{
edges.valueSeq().map(edge => {
const id = edge.get('id');
const fromNode = nodes.get(edge.getIn([ 'from', 'id' ]));
if (!fromNode) { return null; }
const toNode = nodes.get(edge.getIn([ 'to', 'id' ]));
let targetX, targetY;
if (toNode) {
const toNodeInlets = nodeSpecs[toNode.get('type')].spec.inlets.map(prop('id'));
const inletIdx = toNodeInlets.indexOf(edge.getIn([ 'to', 'inlet' ]));
targetX = toNode.get('x') + 12 + 34 * inletIdx;
targetY = toNode.get('y') + 8;
}
else if (id === 'dragging') {
targetX = edge.get('x');
targetY = edge.get('y');
}
return <line
key={ id }
onClick={ () => this.onClickEdge(id) }
className={ classNames('edge', { 'edge--selected': selectedId === id }) }
x1={ fromNode.get('x') + 12 }
y1={ fromNode.get('y') + 96 }
x2={ targetX }
y2={ targetY }
/>
})
}
</svg>;
}
}
const mapDispatchToProps = (dispatch) => bindActionCreators({ deleteEdge }, dispatch);
export default connect(null, mapDispatchToProps)(enhanceWithClickOutside(EditorEdges));
|
src/parser/monk/brewmaster/modules/spells/azeritetraits/TrainingOfNiuzao.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import { calculateAzeriteEffects } from 'common/stats';
import { formatNumber, formatPercentage } from 'common/format';
import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox';
import StatTracker from 'parser/shared/modules/StatTracker';
const TON_SCALE = {
[SPELLS.LIGHT_STAGGER_DEBUFF.id]: 1,
[SPELLS.MODERATE_STAGGER_DEBUFF.id]: 2,
[SPELLS.HEAVY_STAGGER_DEBUFF.id]: 3,
};
export function trainingOfNiuzaoStats(combatant) {
if(!combatant.hasTrait(SPELLS.TRAINING_OF_NIUZAO.id)) {
return null;
}
return {
mastery: combatant.traitsBySpellId[SPELLS.TRAINING_OF_NIUZAO.id]
.reduce((total, rank) => total + calculateAzeriteEffects(SPELLS.TRAINING_OF_NIUZAO.id, rank)[0], 0),
};
}
const NULL_MASTERY = { mastery: 0 };
/**
* Training of Niuzao
*
* Gain up to X mastery based on your level of Stagger.
*
* The effect size from scaling code is actually the amount given at
* *Light* stagger, not the tooltip value.
*
* Scaling calculation is disconnected from this class so it can be
* re-used by the StatTracker.
*
* Example Report: https://www.warcraftlogs.com/reports/X4kZzGnym1YMJwPd/#fight=32&source=7
*/
class TrainingOfNiuzao extends Analyzer {
static dependencies = {
statTracker: StatTracker,
};
mastery = 0;
constructor(...args) {
super(...args);
if(!this.selectedCombatant.hasTrait(SPELLS.TRAINING_OF_NIUZAO.id)) {
this.active = false;
return;
}
this.mastery = trainingOfNiuzaoStats(this.selectedCombatant).mastery;
this.statTracker.add(SPELLS.LIGHT_STAGGER_DEBUFF.id, {
mastery: combatant => (trainingOfNiuzaoStats(combatant) || NULL_MASTERY).mastery * TON_SCALE[SPELLS.LIGHT_STAGGER_DEBUFF.id],
});
this.statTracker.add(SPELLS.MODERATE_STAGGER_DEBUFF.id, {
mastery: combatant => (trainingOfNiuzaoStats(combatant) || NULL_MASTERY).mastery * TON_SCALE[SPELLS.MODERATE_STAGGER_DEBUFF.id],
});
this.statTracker.add(SPELLS.HEAVY_STAGGER_DEBUFF.id, {
mastery: combatant => (trainingOfNiuzaoStats(combatant) || NULL_MASTERY).mastery * TON_SCALE[SPELLS.HEAVY_STAGGER_DEBUFF.id],
});
}
get avgMastery() {
return Object.entries(TON_SCALE).reduce((current, [buff, scale]) => this.selectedCombatant.getBuffUptime(buff) / this.owner.fightDuration * scale * this.mastery + current, 0);
}
statistic() {
const lightUptime = this.selectedCombatant.getBuffUptime(SPELLS.LIGHT_STAGGER_DEBUFF.id) / this.owner.fightDuration;
const moderateUptime = this.selectedCombatant.getBuffUptime(SPELLS.MODERATE_STAGGER_DEBUFF.id) / this.owner.fightDuration;
const heavyUptime = this.selectedCombatant.getBuffUptime(SPELLS.HEAVY_STAGGER_DEBUFF.id) / this.owner.fightDuration;
const lightMastery = TON_SCALE[SPELLS.LIGHT_STAGGER_DEBUFF.id] * this.mastery;
const moderateMastery = TON_SCALE[SPELLS.MODERATE_STAGGER_DEBUFF.id] * this.mastery;
const heavyMastery = TON_SCALE[SPELLS.HEAVY_STAGGER_DEBUFF.id] * this.mastery;
// the `this.owner.getModule(StatTracker)` bit is used because atm
// StatTracker ALSO imports this module so that the mastery
// calculation isn't done inline over there. it is possible to
// import StatTracker, but not to set it as a dependency.
return (
<TraitStatisticBox
position={STATISTIC_ORDER.OPTIONAL()}
trait={SPELLS.TRAINING_OF_NIUZAO.id}
value={`${formatPercentage(this.statTracker.masteryPercentage(this.avgMastery, false))}% Avg. Mastery`}
tooltip={(
<>
Contribution Breakdown:
<ul>
<li>No Stagger: <strong>{formatPercentage(1 - lightUptime - moderateUptime - heavyUptime)}%</strong> of the fight.</li>
<li>Light Stagger: <strong>{formatPercentage(lightUptime)}%</strong> of the fight at <strong>{formatNumber(lightMastery)} Mastery</strong>.</li>
<li>Moderate Stagger: <strong>{formatPercentage(moderateUptime)}%</strong> of the fight at <strong>{formatNumber(moderateMastery)} Mastery</strong>.</li>
<li>Heavy Stagger: <strong>{formatPercentage(heavyUptime)}%</strong> of the fight at <strong>{formatNumber(heavyMastery)} Mastery</strong>.</li>
</ul>
</>
)}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
}
export default TrainingOfNiuzao;
|
src/pages/maker-party/activities/mixin.js | mozilla/advocacy.mozilla.org | import React from 'react'
module.exports = {
componentDidMount: function() {
var navTop, navEl, windowHeight, navHeight;
navEl = document.querySelector(".agenda-navigation");
var navOffset = navEl.getBoundingClientRect();
navTop = navOffset.top;
navigate(window.location.hash);
function hide(el) {
el.style.display = "none";
}
function show(el) {
el.style.display = "block";
}
function forEachList(list, callback) {
Array.prototype.forEach.call(list, callback);
}
function applyAll(list, event, callback) {
forEachList(list, function(item) {
item.addEventListener(event, callback);
});
}
applyAll(navEl.querySelectorAll('a'), "click", function(e) {
e.preventDefault();
navigate(this.getAttribute("href"));
});
function navigate(hash) {
if (!hash) {
return;
}
// First, we'll hide all of the content
forEachList(document.querySelectorAll(".agenda > li"), function(item) {
hide(item);
});
hide(document.querySelector("section.overview"));
// Next, we'll try to figure out what step to show based on the hash.
hash = hash.toLowerCase();
var numberOfSteps = document.querySelectorAll(".agenda > li").length;
var overview = true;
if(hash.indexOf("step") > 0) {
var step = hash.replace("#step-","");
if(step <= numberOfSteps){
overview = false;
}
}
// If there's a step number in the hash, we'll show that step.
// Otherwise, we'll default to the overview.
if(overview) {
hash = "#overview";
show(document.querySelector("section.overview"));
document.querySelector(".wrapper").setAttribute("mode","overview");
} else {
show(document.querySelector(".agenda > li:nth-child("+step+")"));
document.querySelector(".wrapper").setAttribute("mode","step");
}
// Here we add the selected class to the activity navigation link.
var selected = navEl.querySelector(".selected");
if (selected) {
selected.classList.remove("selected");
}
navEl.querySelector("a[href='"+hash+"']").parentNode.classList.add("selected");
window.location.hash = hash;
}
}
};
|
ajax/libs/rxjs/2.3.7/rx.all.js | mikelambert/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var BooleanDisposable = (function () {
function BooleanDisposable (isSingle) {
this.isSingle = isSingle;
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
if (this.current && this.isSingle) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
inherits(SingleAssignmentDisposable, super_);
function SingleAssignmentDisposable() {
super_.call(this, true);
}
return SingleAssignmentDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
var SerialDisposable = Rx.SerialDisposable = (function (super_) {
inherits(SerialDisposable, super_);
function SerialDisposable() {
super_.call(this, false);
}
return SerialDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var s = state;
var id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @private */
var CatchScheduler = (function (_super) {
function localNow() {
return this._scheduler.now();
}
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, _super);
/** @private */
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
/** @private */
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
/** @private */
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
/** @private */
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
/** @private */
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @private */
var ObserveOnObserver = (function (_super) {
inherits(ObserveOnObserver, _super);
/** @private */
function ObserveOnObserver() {
_super.apply(this, arguments);
}
/** @private */
ObserveOnObserver.prototype.next = function (value) {
_super.prototype.next.call(this, value);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.error = function (e) {
_super.prototype.error.call(this, e);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.completed = function () {
_super.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
return function () {
if (promise && promise.abort) {
promise.abort();
}
}
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function isIterable(o) {
return o[$iterator$] !== undefined;
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
function isCallable(f) {
return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isCallable(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var list = Object(iterable),
objIsIterable = isIterable(list),
len = objIsIterable ? 0 : toLength(list),
it = objIsIterable ? list[$iterator$]() : null,
i = 0;
return scheduler.scheduleRecursive(function (self) {
if (i < len || objIsIterable) {
var result;
if (objIsIterable) {
var next = it.next();
if (next.done) {
observer.onCompleted();
return;
}
result = next.value;
} else {
result = list[i];
}
if (mapFn && isCallable(mapFn)) {
try {
result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throw(new Error('Error'));
* var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
if (resource) {
disposable = resource;
}
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
if (isPromise(xs)) { xs = observableFromPromise(xs); }
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) { observer.onCompleted(); }
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) { observer.onCompleted(); }
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) {
throw new Error('Second observable is required');
}
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
self();
}, function () {
self();
}));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.do(observer);
* var res = observable.do(onNext);
* var res = observable.do(onNext, onError);
* var res = observable.do(onNext, onError, onCompleted);
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (!onError) {
observer.onError(err);
} else {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
*
* @example
* var res = source.takeLast(5);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while(q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
if (count <= 0) {
throw new Error(argumentOutOfRange);
}
if (arguments.length === 1) {
skip = count;
}
if (skip <= 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [],
createWindow = function () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
};
createWindow();
m.setDisposable(source.subscribe(function (x) {
var s;
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
var c = n - count + 1;
if (c >= 0 && c % skip === 0) {
s = q.shift();
s.onCompleted();
}
n++;
if (n % skip === 0) {
createWindow();
}
}, function (exception) {
while (q.length > 0) {
q.shift().onError(exception);
}
observer.onError(exception);
}, function () {
while (q.length > 0) {
q.shift().onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
return typeof selector === 'function' ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && observer.onNext(x);
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
}, thisArg);
}
return typeof selector === 'function' ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (observer) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
observer.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
observer.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) {
list.push(x);
}
}, observer.onError.bind(observer), function () {
observer.onNext(list);
observer.onCompleted();
});
});
}
function firstOnly(x) {
if (x.length === 0) {
throw new Error(sequenceContainsNoElements);
}
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.aggregate(function (acc, x) { return acc + x; });
* 2 - res = source.aggregate(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var seed, hasSeed, accumulator;
if (arguments.length === 2) {
seed = arguments[0];
hasSeed = true;
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.reduce(function (acc, x) { return acc + x; });
* 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0);
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var seed, hasSeed;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @example
* var result = source.any();
* var result = source.any(function (x) { return x > 3; });
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = observableProto.any = function (predicate, thisArg) {
var source = this;
return predicate ?
source.where(predicate, thisArg).any() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
observer.onNext(false);
observer.onCompleted();
});
});
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
*
* 1 - res = source.all(function (value) { return value.length > 3; });
* @memberOf Observable#
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = observableProto.all = function (predicate, thisArg) {
return this.where(function (v) {
return !predicate(v);
}, thisArg).any().select(function (b) {
return !b;
});
};
/**
* Determines whether an observable sequence contains a specified element with an optional equality comparer.
* @example
* 1 - res = source.contains(42);
* 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; });
* @param value The value to locate in the source sequence.
* @param {Function} [comparer] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value.
*/
observableProto.contains = function (value, comparer) {
comparer || (comparer = defaultComparer);
return this.where(function (v) {
return comparer(v, value);
}).any();
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).count() :
this.aggregate(0, function (count) {
return count + 1;
});
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @example
* var res = source.sum();
* var res = source.sum(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).sum() :
this.aggregate(0, function (prev, curr) {
return prev + curr;
});
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) {
return comparer(x, y) * -1;
});
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @example
* var res = res = source.average();
* var res = res = source.average(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).average() :
this.scan({
sum: 0,
count: 0
}, function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}).finalValue().select(function (s) {
if (s.count === 0) {
throw new Error('The input sequence was empty');
}
return s.sum / s.count;
});
};
function sequenceEqualArray(first, second, comparer) {
return new AnonymousObservable(function (observer) {
var count = 0, len = second.length;
return first.subscribe(function (value) {
var equal = false;
try {
if (count < len) {
equal = comparer(value, second[count++]);
}
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
}, observer.onError.bind(observer), function () {
observer.onNext(count === len);
observer.onCompleted();
});
});
}
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
if (Array.isArray(second)) {
return sequenceEqualArray(first, second, comparer);
}
return new AnonymousObservable(function (observer) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (doner) {
observer.onNext(false);
observer.onCompleted();
} else {
ql.push(x);
}
}, observer.onError.bind(observer), function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (doner) {
observer.onNext(true);
observer.onCompleted();
}
}
});
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal, v;
if (ql.length > 0) {
v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
observer.onError(exception);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (donel) {
observer.onNext(false);
observer.onCompleted();
} else {
qr.push(x);
}
}, observer.onError.bind(observer), function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (donel) {
observer.onNext(true);
observer.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
});
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var i = index;
return source.subscribe(function (x) {
if (i === 0) {
observer.onNext(x);
observer.onCompleted();
}
i--;
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(argumentOutOfRange));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
observer.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @example
* var res = res = source.single();
* var res = res = source.single(function (x) { return x === 42; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate?
this.where(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue)
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
observer.onNext(x);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = res = source.firstOrDefault();
* var res = res = source.firstOrDefault(function (x) { return x > 3; });
* var res = source.firstOrDefault(function (x) { return x > 3; }, 0);
* var res = source.firstOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @example
* var res = source.last();
* var res = source.last(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = source.lastOrDefault();
* var res = source.lastOrDefault(function (x) { return x > 3; });
* var res = source.lastOrDefault(function (x) { return x > 3; }, 0);
* var res = source.lastOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
return new AnonymousObservable(function (observer) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, x, i, source);
} catch(e) {
observer.onError(e);
return;
}
if (shouldRun) {
observer.onNext(yieldIndex ? i : x);
observer.onCompleted();
} else {
i++;
}
}, observer.onError.bind(observer), function () {
observer.onNext(yieldIndex ? -1 : undefined);
observer.onCompleted();
});
});
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
*
* @example
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);
* var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');
*
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
// Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs
// for proper loading order!
var marionette = !!root.Backbone && !!root.Backbone.Marionette;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
if (marionette) {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.subject.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.subject.distinctUntilChanged(),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
observer.onNext(q.shift());
}
}
} else {
// new data
if (results.shouldFire) {
observer.onNext(results.data);
} else {
q.push(results.data);
}
}
previousShouldFire = results.shouldFire;
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
this.subject.onNext(false);
return subscription;
}
function PausableBufferedObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (enableQueue == null) {
enableQueue = true;
}
_super.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return !selector ?
this.multicast(new Subject()) :
this.multicast(function () {
return new Subject();
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.share();
*
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish(null).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return !selector ?
this.multicast(new AsyncSubject()) :
this.multicast(function () {
return new AsyncSubject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareValue(42);
*
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).
refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return !selector ?
this.multicast(new ReplaySubject(bufferSize, window, scheduler)) :
this.multicast(function () {
return new ReplaySubject(bufferSize, window, scheduler);
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, _super);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
_super.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (_super) {
function RemovableDisposable (subject, observer) {
this.subject = subject;
this.observer = observer;
};
RemovableDisposable.prototype.dispose = function () {
this.observer.dispose();
if (!this.subject.isDisposed) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
}
};
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = new RemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, _super);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
_super.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/* @private */
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, subject.subscribe.bind(subject));
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if (candidate & 1 === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof obj === 'string') { return stringHashFn(valueOf); }
}
if (obj.getHashCode) { return obj.getHashCode(); }
var id = 17 * uniqueIdCounter++;
obj.getHashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new Error('out of range'); }
if (capacity > 0) { this._initialize(capacity); }
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
}
var dictionaryProto = Dictionary.prototype;
dictionaryProto._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
dictionaryProto.add = function (key, value) {
return this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch(exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
});
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, function () {
return observableEmpty();
}, function (_, window) {
return window;
});
}
function observableWindowWithBounaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var window = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
d.add(windowBoundaries.subscribe(function (w) {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
return r;
});
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var createWindowClose,
m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
window = new Subject();
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
createWindowClose = function () {
var m1, windowClose;
try {
windowClose = windowClosingSelector();
} catch (exception) {
observer.onError(exception);
return;
}
m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
createWindowClose();
}));
};
createWindowClose();
return r;
});
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
var published = this.publish().refCount();
return [
published.filter(predicate, thisArg),
published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector) {
return enumerableFor(sources, resultSelector).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
});
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
});
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeObservable().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwException(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = (function () {
/**
* @constructor
* @private
*/
function Map() {
this.keys = [];
this.values = [];
}
/**
* @private
* @memberOf Map#
*/
Map.prototype['delete'] = function (key) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.keys.splice(i, 1);
this.values.splice(i, 1);
}
return i !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.get = function (key, fallback) {
var i = this.keys.indexOf(key);
return i !== -1 ? this.values[i] : fallback;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.set = function (key, value) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.values[i] = value;
}
this.values[this.keys.push(key) - 1] = value;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.size = function () { return this.keys.length; };
/**
* @private
* @memberOf Map#
*/
Map.prototype.has = function (key) {
return this.keys.indexOf(key) !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.getKeys = function () { return this.keys.slice(0); };
/**
* @private
* @memberOf Map#
*/
Map.prototype.getValues = function () { return this.values.slice(0); };
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
*
* @param other Observable sequence to match in addition to the current pattern.
* @return Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
var patterns = this.patterns.slice(0);
patterns.push(other);
return new Pattern(patterns);
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
*
* @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
// Active Plan
function ActivePlan(joinObserverArray, onNext, onCompleted) {
var i, joinObserver;
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (i = 0; i < this.joinObserverArray.length; i++) {
joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
var values = this.joinObservers.getValues();
for (var i = 0, len = values.length; i < len; i++) {
values[i].queue.shift();
}
};
ActivePlan.prototype.match = function () {
var firstValues, i, len, isCompleted, values, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
firstValues = [];
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
if (this.joinObserverArray[i].queue[0].kind === 'C') {
isCompleted = true;
}
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
values = [];
for (i = 0; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
/** @private */
var JoinObserver = (function (_super) {
inherits(JoinObserver, _super);
/**
* @constructor
* @private
*/
function JoinObserver(source, onError) {
_super.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
this.onError(notification.exception);
return;
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.error = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.completed = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.removeActivePlan = function (activePlan) {
var idx = this.activePlans.indexOf(activePlan);
this.activePlans.splice(idx, 1);
if (this.activePlans.length === 0) {
this.dispose();
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var plans = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var activePlans = [],
externalSubscriptions = new Map(),
group,
i, len,
joinObserver,
joinValues,
outObserver;
outObserver = observerCreate(observer.onNext.bind(observer), function (exception) {
var values = externalSubscriptions.getValues();
for (var j = 0, jlen = values.length; j < jlen; j++) {
values[j].onError(exception);
}
observer.onError(exception);
}, observer.onCompleted.bind(observer));
try {
for (i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
if (activePlans.length === 0) {
outObserver.onCompleted();
}
}));
}
} catch (e) {
observableThrow(e).subscribe(observer);
}
group = new CompositeDisposable();
joinValues = externalSubscriptions.getValues();
for (i = 0, len = joinValues.length; i < len; i++) {
joinObserver = joinValues[i];
joinObserver.subscribe();
group.add(joinObserver);
}
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count++);
self(d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
*
* @example
* 1 - res = Rx.Observable.timer(new Date());
* 2 - res = Rx.Observable.timer(new Date(), 1000);
* 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout);
*
* 5 - res = Rx.Observable.timer(5000);
* 6 - res = Rx.Observable.timer(5000, 1000);
* 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
*
* @example
* 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (typeof timeShiftOrScheduler === 'object') {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(function (x) {
var i, len;
for (i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
}, function (e) {
var i, len;
for (i = 0, len = q.length; i < len; i++) {
q[i].onError(e);
}
observer.onError(e);
}, function () {
var i, len;
for (i = 0, len = q.length; i < len; i++) {
q[i].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
function createTimer () {
var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
isSpan && (nextSpan += timeShift);
isShift && (nextShift += timeShift);
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
var s;
if (isShift) {
s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
if (isSpan) {
s = q.shift();
s.onCompleted();
}
createTimer();
}));
}
});
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @example
* 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items
* 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items
*
* @memberOf Observable#
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var createTimer,
groupDisposable,
n = 0,
refCountDisposable,
s = new Subject()
timerD = new SerialDisposable(),
windowId = 0;
groupDisposable = new CompositeDisposable(timerD);
refCountDisposable = new RefCountDisposable(groupDisposable);
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
n++;
if (n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
}, function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}));
return refCountDisposable;
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
var newId;
if (id !== windowId) { return; }
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return { value: x, interval: span };
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
*
* @example
* 1 - res = source.timeout(new Date()); // As a date
* 2 - res = source.timeout(5000); // 5 seconds
* 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable
* 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable
* 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable
* 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
other || (other = observableThrow(new Error('Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
var createTimer = function () {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
*
* @example
* 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500));
* 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); });
* 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42));
*
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
var firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false, setTimer = function (timeout) {
var myId = id, timerWins = function () {
return id === myId;
};
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
d.dispose();
}, function (e) {
if (timerWins()) {
observer.onError(e);
}
}, function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
setTimer(firstTimeout);
var observerWins = function () {
var res = !switched;
if (res) {
id++;
}
return res;
};
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(timeout);
}
}, function (e) {
if (observerWins()) {
observer.onError(e);
}
}, function () {
if (observerWins()) {
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); });
*
* @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttleWithSelector = function (throttleDurationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
if (hasValue) {
observer.onNext(value);
}
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
*
* @example
* 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
observer.onNext(next.value);
}
}
observer.onCompleted();
});
});
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
res.push(next.value);
}
}
observer.onNext(res);
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
});
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [optional scheduler]);
* @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && observer.onNext(x); },
observer.onError.bind(observer),
observer.onCompleted.bind(observer)));
});
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]);
* 2 - res = source.takeUntilWithTime(5000, [optional scheduler]);
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} scheduler Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () {
observer.onCompleted();
}), source.subscribe(observer));
});
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function notImplemented() {
throw new Error('Not implemented');
}
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new Error(argumentOutOfRange); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (__super__) {
inherits(HistoricalScheduler, __super__);
/**
* Creates a new historical scheduler with the specified initial clock value.
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
__super__.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var GroupedObservable = (function (_super) {
inherits(GroupedObservable, _super);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
/**
* @constructor
* @private
*/
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
_super.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
src/components/Feedback/Feedback.js | louisukiri/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Feedback.css';
class Feedback extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<a
className={s.link}
href="https://gitter.im/kriasoft/react-starter-kit"
>
Ask a question
</a>
<span className={s.spacer}>|</span>
<a
className={s.link}
href="https://github.com/kriasoft/react-starter-kit/issues/new"
>
Report an issue
</a>
</div>
</div>
);
}
}
export default withStyles(s)(Feedback);
|
ajax/libs/analytics.js/1.5.0/analytics.js | snorpey/cdnjs | ;(function(){
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(path, parent, orig) {
var resolved = require.resolve(path);
// lookup failed
if (null == resolved) {
orig = orig || path;
parent = parent || 'root';
var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
err.path = orig;
err.parent = parent;
err.require = true;
throw err;
}
var module = require.modules[resolved];
// perform real require()
// by invoking the module's
// registered function
if (!module._resolving && !module.exports) {
var mod = {};
mod.exports = {};
mod.client = mod.component = true;
module._resolving = true;
module.call(this, mod.exports, require.relative(resolved), mod);
delete module._resolving;
module.exports = mod.exports;
}
return module.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path) {
if (path.charAt(0) === '/') path = path.slice(1);
var paths = [
path,
path + '.js',
path + '.json',
path + '/index.js',
path + '/index.json'
];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (require.modules.hasOwnProperty(path)) return path;
if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
}
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `definition`.
*
* @param {String} path
* @param {Function} definition
* @api private
*/
require.register = function(path, definition) {
require.modules[path] = definition;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to) {
if (!require.modules.hasOwnProperty(from)) {
throw new Error('Failed to alias "' + from + '", it does not exist');
}
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function localRequire(path) {
var resolved = localRequire.resolve(path);
return require(resolved, parent, path);
}
/**
* Resolve relative to the parent.
*/
localRequire.resolve = function(path) {
var c = path.charAt(0);
if ('/' == c) return path.slice(1);
if ('.' == c) return require.normalize(p, path);
// resolve deps by returning
// the dep in the nearest "deps"
// directory
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
};
/**
* Check if module is defined at `path`.
*/
localRequire.exists = function(path) {
return require.modules.hasOwnProperty(localRequire.resolve(path));
};
return localRequire;
};
require.register("avetisk-defaults/index.js", function(exports, require, module){
'use strict';
/**
* Merge default values.
*
* @param {Object} dest
* @param {Object} defaults
* @return {Object}
* @api public
*/
var defaults = function (dest, src, recursive) {
for (var prop in src) {
if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {
dest[prop] = defaults(dest[prop], src[prop], true);
} else if (! (prop in dest)) {
dest[prop] = src[prop];
}
}
return dest;
};
/**
* Expose `defaults`.
*/
module.exports = defaults;
});
require.register("component-type/index.js", function(exports, require, module){
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object Error]': return 'error';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val !== val) return 'nan';
if (val && val.nodeType === 1) return 'element';
val = val.valueOf
? val.valueOf()
: Object.prototype.valueOf.apply(val)
return typeof val;
};
});
require.register("component-clone/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type;
try {
type = require('type');
} catch(e){
type = require('type-component');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
});
require.register("component-cookie/index.js", function(exports, require, module){
/**
* Encode.
*/
var encode = encodeURIComponent;
/**
* Decode.
*/
var decode = decodeURIComponent;
/**
* Set or get cookie `name` with `value` and `options` object.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {Mixed}
* @api public
*/
module.exports = function(name, value, options){
switch (arguments.length) {
case 3:
case 2:
return set(name, value, options);
case 1:
return get(name);
default:
return all();
}
};
/**
* Set cookie `name` to `value`.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @api private
*/
function set(name, value, options) {
options = options || {};
var str = encode(name) + '=' + encode(value);
if (null == value) options.maxage = -1;
if (options.maxage) {
options.expires = new Date(+new Date + options.maxage);
}
if (options.path) str += '; path=' + options.path;
if (options.domain) str += '; domain=' + options.domain;
if (options.expires) str += '; expires=' + options.expires.toGMTString();
if (options.secure) str += '; secure';
document.cookie = str;
}
/**
* Return all cookies.
*
* @return {Object}
* @api private
*/
function all() {
return parse(document.cookie);
}
/**
* Get cookie `name`.
*
* @param {String} name
* @return {String}
* @api private
*/
function get(name) {
return all()[name];
}
/**
* Parse cookie `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parse(str) {
var obj = {};
var pairs = str.split(/ *; */);
var pair;
if ('' == pairs[0]) return obj;
for (var i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
obj[decode(pair[0])] = decode(pair[1]);
}
return obj;
}
});
require.register("component-each/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type = require('type');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @api public
*/
module.exports = function(obj, fn){
switch (type(obj)) {
case 'array':
return array(obj, fn);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn);
return object(obj, fn);
case 'string':
return string(obj, fn);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @api private
*/
function string(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function object(obj, fn) {
for (var key in obj) {
if (has.call(obj, key)) {
fn(key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @api private
*/
function array(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj[i], i);
}
}
});
require.register("component-indexof/index.js", function(exports, require, module){
module.exports = function(arr, obj){
if (arr.indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
});
require.register("component-emitter/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var index = require('indexof');
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
fn._off = on;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var i = index(callbacks, fn._off || fn);
if (~i) callbacks.splice(i, 1);
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
});
require.register("component-event/index.js", function(exports, require, module){
/**
* Bind `el` event `type` to `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.bind = function(el, type, fn, capture){
if (el.addEventListener) {
el.addEventListener(type, fn, capture || false);
} else {
el.attachEvent('on' + type, fn);
}
return fn;
};
/**
* Unbind `el` event `type`'s callback `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.unbind = function(el, type, fn, capture){
if (el.removeEventListener) {
el.removeEventListener(type, fn, capture || false);
} else {
el.detachEvent('on' + type, fn);
}
return fn;
};
});
require.register("component-inherit/index.js", function(exports, require, module){
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
});
require.register("component-object/index.js", function(exports, require, module){
/**
* HOP ref.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Return own keys in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.keys = Object.keys || function(obj){
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Return own values in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.values = function(obj){
var vals = [];
for (var key in obj) {
if (has.call(obj, key)) {
vals.push(obj[key]);
}
}
return vals;
};
/**
* Merge `b` into `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object} a
* @api public
*/
exports.merge = function(a, b){
for (var key in b) {
if (has.call(b, key)) {
a[key] = b[key];
}
}
return a;
};
/**
* Return length of `obj`.
*
* @param {Object} obj
* @return {Number}
* @api public
*/
exports.length = function(obj){
return exports.keys(obj).length;
};
/**
* Check if `obj` is empty.
*
* @param {Object} obj
* @return {Boolean}
* @api public
*/
exports.isEmpty = function(obj){
return 0 == exports.length(obj);
};
});
require.register("component-trim/index.js", function(exports, require, module){
exports = module.exports = trim;
function trim(str){
if (str.trim) return str.trim();
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
if (str.trimLeft) return str.trimLeft();
return str.replace(/^\s*/, '');
};
exports.right = function(str){
if (str.trimRight) return str.trimRight();
return str.replace(/\s*$/, '');
};
});
require.register("component-querystring/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var encode = encodeURIComponent;
var decode = decodeURIComponent;
var trim = require('trim');
var type = require('type');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = /(\w+)\[(\d+)\]/.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};
});
require.register("component-url/index.js", function(exports, require, module){
/**
* Parse the given `url`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(url){
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
port: a.port,
hash: a.hash,
hostname: a.hostname,
pathname: a.pathname,
protocol: a.protocol,
search: a.search,
query: a.search.slice(1)
}
};
/**
* Check if `url` is absolute.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isAbsolute = function(url){
if (0 == url.indexOf('//')) return true;
if (~url.indexOf('://')) return true;
return false;
};
/**
* Check if `url` is relative.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isRelative = function(url){
return ! exports.isAbsolute(url);
};
/**
* Check if `url` is cross domain.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isCrossDomain = function(url){
url = exports.parse(url);
return url.hostname != location.hostname
|| url.port != location.port
|| url.protocol != location.protocol;
};
});
require.register("component-bind/index.js", function(exports, require, module){
/**
* Slice reference.
*/
var slice = [].slice;
/**
* Bind `obj` to `fn`.
*
* @param {Object} obj
* @param {Function|String} fn or string
* @return {Function}
* @api public
*/
module.exports = function(obj, fn){
if ('string' == typeof fn) fn = obj[fn];
if ('function' != typeof fn) throw new Error('bind() requires a function');
var args = slice.call(arguments, 2);
return function(){
return fn.apply(obj, args.concat(slice.call(arguments)));
}
};
});
require.register("segmentio-bind-all/index.js", function(exports, require, module){
try {
var bind = require('bind');
var type = require('type');
} catch (e) {
var bind = require('bind-component');
var type = require('type-component');
}
module.exports = function (obj) {
for (var key in obj) {
var val = obj[key];
if (type(val) === 'function') obj[key] = bind(obj, obj[key]);
}
return obj;
};
});
require.register("ianstormtaylor-bind/index.js", function(exports, require, module){
try {
var bind = require('bind');
} catch (e) {
var bind = require('bind-component');
}
var bindAll = require('bind-all');
/**
* Expose `bind`.
*/
module.exports = exports = bind;
/**
* Expose `bindAll`.
*/
exports.all = bindAll;
/**
* Expose `bindMethods`.
*/
exports.methods = bindMethods;
/**
* Bind `methods` on `obj` to always be called with the `obj` as context.
*
* @param {Object} obj
* @param {String} methods...
*/
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
});
require.register("timoxley-next-tick/index.js", function(exports, require, module){
"use strict"
if (typeof setImmediate == 'function') {
module.exports = function(f){ setImmediate(f) }
}
// legacy node.js
else if (typeof process != 'undefined' && typeof process.nextTick == 'function') {
module.exports = process.nextTick
}
// fallback for other environments / postMessage behaves badly on IE8
else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) {
module.exports = function(f){ setTimeout(f) };
} else {
var q = [];
window.addEventListener('message', function(){
var i = 0;
while (i < q.length) {
try { q[i++](); }
catch (e) {
q = q.slice(i);
window.postMessage('tic!', '*');
throw e;
}
}
q.length = 0;
}, true);
module.exports = function(fn){
if (!q.length) window.postMessage('tic!', '*');
q.push(fn);
}
}
});
require.register("ianstormtaylor-callback/index.js", function(exports, require, module){
var next = require('next-tick');
/**
* Expose `callback`.
*/
module.exports = callback;
/**
* Call an `fn` back synchronously if it exists.
*
* @param {Function} fn
*/
function callback (fn) {
if ('function' === typeof fn) fn();
}
/**
* Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the
* `fn` will be called on next tick.
*
* @param {Function} fn
* @param {Number} wait (optional)
*/
callback.async = function (fn, wait) {
if ('function' !== typeof fn) return;
if (!wait) return next(fn);
setTimeout(fn, wait);
};
/**
* Symmetry.
*/
callback.sync = callback;
});
require.register("ianstormtaylor-is-empty/index.js", function(exports, require, module){
/**
* Expose `isEmpty`.
*/
module.exports = isEmpty;
/**
* Has.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Test whether a value is "empty".
*
* @param {Mixed} val
* @return {Boolean}
*/
function isEmpty (val) {
if (null == val) return true;
if ('number' == typeof val) return 0 === val;
if (undefined !== val.length) return 0 === val.length;
for (var key in val) if (has.call(val, key)) return false;
return true;
}
});
require.register("ianstormtaylor-is/index.js", function(exports, require, module){
var isEmpty = require('is-empty');
try {
var typeOf = require('type');
} catch (e) {
var typeOf = require('component-type');
}
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
});
require.register("segmentio-after/index.js", function(exports, require, module){
module.exports = function after (times, func) {
// After 0, really?
if (times <= 0) return func();
// That's more like it.
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
});
require.register("component-domify/index.js", function(exports, require, module){
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default: [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return the children.
*
* @param {String} html
* @return {Array}
* @api private
*/
function parse(html) {
if ('string' != typeof html) throw new TypeError('String expected');
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return document.createTextNode(html);
var tag = m[1];
// body support
if (tag == 'body') {
var el = document.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = document.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = document.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
}
});
require.register("component-once/index.js", function(exports, require, module){
/**
* Identifier.
*/
var n = 0;
/**
* Global.
*/
var global = (function(){ return this })();
/**
* Make `fn` callable only once.
*
* @param {Function} fn
* @return {Function}
* @api public
*/
module.exports = function(fn) {
var id = n++;
function once(){
// no receiver
if (this == global) {
if (once.called) return;
once.called = true;
return fn.apply(this, arguments);
}
// receiver
var key = '__called_' + id + '__';
if (this[key]) return;
this[key] = true;
return fn.apply(this, arguments);
}
return once;
};
});
require.register("segmentio-alias/index.js", function(exports, require, module){
var type = require('type');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `alias`.
*/
module.exports = alias;
/**
* Alias an `object`.
*
* @param {Object} obj
* @param {Mixed} method
*/
function alias (obj, method) {
switch (type(method)) {
case 'object': return aliasByDictionary(clone(obj), method);
case 'function': return aliasByFunction(clone(obj), method);
}
}
/**
* Convert the keys in an `obj` using a dictionary of `aliases`.
*
* @param {Object} obj
* @param {Object} aliases
*/
function aliasByDictionary (obj, aliases) {
for (var key in aliases) {
if (undefined === obj[key]) continue;
obj[aliases[key]] = obj[key];
delete obj[key];
}
return obj;
}
/**
* Convert the keys in an `obj` using a `convert` function.
*
* @param {Object} obj
* @param {Function} convert
*/
function aliasByFunction (obj, convert) {
// have to create another object so that ie8 won't infinite loop on keys
var output = {};
for (var key in obj) output[convert(key)] = obj[key];
return output;
}
});
require.register("ianstormtaylor-to-no-case/index.js", function(exports, require, module){
/**
* Expose `toNoCase`.
*/
module.exports = toNoCase;
/**
* Test whether a string is camel-case.
*/
var hasSpace = /\s/;
var hasCamel = /[a-z][A-Z]/;
var hasSeparator = /[\W_]/;
/**
* Remove any starting case from a `string`, like camel or snake, but keep
* spaces and punctuation that may be important otherwise.
*
* @param {String} string
* @return {String}
*/
function toNoCase (string) {
if (hasSpace.test(string)) return string.toLowerCase();
if (hasSeparator.test(string)) string = unseparate(string);
if (hasCamel.test(string)) string = uncamelize(string);
return string.toLowerCase();
}
/**
* Separator splitter.
*/
var separatorSplitter = /[\W_]+(.|$)/g;
/**
* Un-separate a `string`.
*
* @param {String} string
* @return {String}
*/
function unseparate (string) {
return string.replace(separatorSplitter, function (m, next) {
return next ? ' ' + next : '';
});
}
/**
* Camelcase splitter.
*/
var camelSplitter = /(.)([A-Z]+)/g;
/**
* Un-camelcase a `string`.
*
* @param {String} string
* @return {String}
*/
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
});
require.register("segmentio-analytics.js-integration/lib/index.js", function(exports, require, module){
var bind = require('bind');
var callback = require('callback');
var clone = require('clone');
var debug = require('debug');
var defaults = require('defaults');
var protos = require('./protos');
var slug = require('slug');
var statics = require('./statics');
/**
* Expose `createIntegration`.
*/
module.exports = createIntegration;
/**
* Create a new Integration constructor.
*
* @param {String} name
*/
function createIntegration (name) {
/**
* Initialize a new `Integration`.
*
* @param {Object} options
*/
function Integration (options) {
this.debug = debug('analytics:integration:' + slug(name));
this.options = defaults(clone(options) || {}, this.defaults);
this._queue = [];
this.once('ready', bind(this, this.flush));
Integration.emit('construct', this);
this._wrapInitialize();
this._wrapLoad();
this._wrapPage();
this._wrapTrack();
}
Integration.prototype.defaults = {};
Integration.prototype.globals = [];
Integration.prototype.name = name;
for (var key in statics) Integration[key] = statics[key];
for (var key in protos) Integration.prototype[key] = protos[key];
return Integration;
}
});
require.register("segmentio-analytics.js-integration/lib/protos.js", function(exports, require, module){
/**
* Module dependencies.
*/
var normalize = require('to-no-case');
var after = require('after');
var callback = require('callback');
var Emitter = require('emitter');
var tick = require('next-tick');
var events = require('./events');
var type = require('type');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Initialize.
*/
exports.initialize = function () {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
* @api private
*/
exports.loaded = function () {
return false;
};
/**
* Load.
*
* @param {Function} cb
*/
exports.load = function (cb) {
callback.async(cb);
};
/**
* Page.
*
* @param {Page} page
*/
exports.page = function(page){};
/**
* Track.
*
* @param {Track} track
*/
exports.track = function(track){};
/**
* Get events that match `str`.
*
* Examples:
*
* events = { my_event: 'a4991b88' }
* .map(events, 'My Event');
* // => ["a4991b88"]
* .map(events, 'whatever');
* // => []
*
* events = [{ key: 'my event', value: '9b5eb1fa' }]
* .map(events, 'my_event');
* // => ["9b5eb1fa"]
* .map(events, 'whatever');
* // => []
*
* @param {String} str
* @return {Array}
* @api public
*/
exports.map = function(obj, str){
var a = normalize(str);
var ret = [];
// noop
if (!obj) return ret;
// object
if ('object' == type(obj)) {
for (var k in obj) {
var item = obj[k];
var b = normalize(k);
if (b == a) ret.push(item);
}
}
// array
if ('array' == type(obj)) {
if (!obj.length) return ret;
if (!obj[0].key) return ret;
for (var i = 0; i < obj.length; ++i) {
var item = obj[i];
var b = normalize(item.key);
if (b == a) ret.push(item.value);
}
}
return ret;
};
/**
* Invoke a `method` that may or may not exist on the prototype with `args`,
* queueing or not depending on whether the integration is "ready". Don't
* trust the method call, since it contains integration party code.
*
* @param {String} method
* @param {Mixed} args...
* @api private
*/
exports.invoke = function (method) {
if (!this[method]) return;
var args = [].slice.call(arguments, 1);
if (!this._ready) return this.queue(method, args);
var ret;
try {
this.debug('%s with %o', method, args);
ret = this[method].apply(this, args);
} catch (e) {
this.debug('error %o calling %s with %o', e, method, args);
}
return ret;
};
/**
* Queue a `method` with `args`. If the integration assumes an initial
* pageview, then let the first call to `page` pass through.
*
* @param {String} method
* @param {Array} args
* @api private
*/
exports.queue = function (method, args) {
if ('page' == method && this._assumesPageview && !this._initialized) {
return this.page.apply(this, args);
}
this._queue.push({ method: method, args: args });
};
/**
* Flush the internal queue.
*
* @api private
*/
exports.flush = function () {
this._ready = true;
var call;
while (call = this._queue.shift()) this[call.method].apply(this, call.args);
};
/**
* Reset the integration, removing its global variables.
*
* @api private
*/
exports.reset = function () {
for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined;
};
/**
* Wrap the initialize method in an exists check, so we don't have to do it for
* every single integration.
*
* @api private
*/
exports._wrapInitialize = function () {
var initialize = this.initialize;
this.initialize = function () {
this.debug('initialize');
this._initialized = true;
var ret = initialize.apply(this, arguments);
this.emit('initialize');
var self = this;
if (this._readyOnInitialize) {
tick(function () {
self.emit('ready');
});
}
return ret;
};
if (this._assumesPageview) this.initialize = after(2, this.initialize);
};
/**
* Wrap the load method in `debug` calls, so every integration gets them
* automatically.
*
* @api private
*/
exports._wrapLoad = function () {
var load = this.load;
this.load = function (callback) {
var self = this;
this.debug('loading');
if (this.loaded()) {
this.debug('already loaded');
tick(function () {
if (self._readyOnLoad) self.emit('ready');
callback && callback();
});
return;
}
return load.call(this, function (err, e) {
self.debug('loaded');
self.emit('load');
if (self._readyOnLoad) self.emit('ready');
callback && callback(err, e);
});
};
};
/**
* Wrap the page method to call `initialize` instead if the integration assumes
* a pageview.
*
* @api private
*/
exports._wrapPage = function () {
var page = this.page;
this.page = function () {
if (this._assumesPageview && !this._initialized) {
return this.initialize.apply(this, arguments);
}
return page.apply(this, arguments);
};
};
/**
* Wrap the track method to call other ecommerce methods if
* available depending on the `track.event()`.
*
* @api private
*/
exports._wrapTrack = function(){
var t = this.track;
this.track = function(track){
var event = track.event();
var called;
var ret;
for (var method in events) {
var regexp = events[method];
if (!this[method]) continue;
if (!regexp.test(event)) continue;
ret = this[method].apply(this, arguments);
called = true;
break;
}
if (!called) ret = t.apply(this, arguments);
return ret;
};
};
});
require.register("segmentio-analytics.js-integration/lib/events.js", function(exports, require, module){
/**
* Expose `events`
*/
module.exports = {
removedProduct: /removed[ _]?product/i,
viewedProduct: /viewed[ _]?product/i,
addedProduct: /added[ _]?product/i,
completedOrder: /completed[ _]?order/i
};
});
require.register("segmentio-analytics.js-integration/lib/statics.js", function(exports, require, module){
var after = require('after');
var Emitter = require('emitter');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Add a new option to the integration by `key` with default `value`.
*
* @param {String} key
* @param {Mixed} value
* @return {Integration}
*/
exports.option = function (key, value) {
this.prototype.defaults[key] = value;
return this;
};
/**
* Add a new mapping option.
*
* the method will create a method `name` that will return a mapping
* for you to use.
*
* Example:
*
* Integration('My Integration')
* .mapping('events');
*
* new MyIntegration().track('My Event');
*
* .track = function(track){
* var events = this.events(track.event());
* each(events, send);
* };
*
* @param {String} name
* @return {Integration}
* @api public
*/
exports.mapping = function(name){
this.option(name, []);
this.prototype[name] = function(str){
return this.map(this.options[name], str);
};
return this;
};
/**
* Register a new global variable `key` owned by the integration, which will be
* used to test whether the integration is already on the page.
*
* @param {String} global
* @return {Integration}
*/
exports.global = function (key) {
this.prototype.globals.push(key);
return this;
};
/**
* Mark the integration as assuming an initial pageview, so to defer loading
* the script until the first `page` call, noop the first `initialize`.
*
* @return {Integration}
*/
exports.assumesPageview = function () {
this.prototype._assumesPageview = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnLoad = function () {
this.prototype._readyOnLoad = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnInitialize = function () {
this.prototype._readyOnInitialize = true;
return this;
};
});
require.register("segmentio-convert-dates/index.js", function(exports, require, module){
var is = require('is');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `convertDates`.
*/
module.exports = convertDates;
/**
* Recursively convert an `obj`'s dates to new values.
*
* @param {Object} obj
* @param {Function} convert
* @return {Object}
*/
function convertDates (obj, convert) {
obj = clone(obj);
for (var key in obj) {
var val = obj[key];
if (is.date(val)) obj[key] = convert(val);
if (is.object(val)) obj[key] = convertDates(val, convert);
}
return obj;
}
});
require.register("segmentio-global-queue/index.js", function(exports, require, module){
/**
* Expose `generate`.
*/
module.exports = generate;
/**
* Generate a global queue pushing method with `name`.
*
* @param {String} name
* @param {Object} options
* @property {Boolean} wrap
* @return {Function}
*/
function generate (name, options) {
options = options || {};
return function (args) {
args = [].slice.call(arguments);
window[name] || (window[name] = []);
options.wrap === false
? window[name].push.apply(window[name], args)
: window[name].push(args);
};
}
});
require.register("segmentio-load-date/index.js", function(exports, require, module){
/*
* Load date.
*
* For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/
*/
var time = new Date()
, perf = window.performance;
if (perf && perf.timing && perf.timing.responseEnd) {
time = new Date(perf.timing.responseEnd);
}
module.exports = time;
});
require.register("segmentio-load-script/index.js", function(exports, require, module){
var type = require('type');
module.exports = function loadScript (options, callback) {
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if (type(options) === 'string') options = { src : options };
var https = document.location.protocol === 'https:' ||
document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
// If we have a callback, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if (callback && type(callback) === 'function') {
if (script.addEventListener) {
script.addEventListener('load', function (event) {
callback(null, event);
}, false);
script.addEventListener('error', function (event) {
callback(new Error('Failed to load the script.'), event);
}, false);
} else if (script.attachEvent) {
script.attachEvent('onreadystatechange', function (event) {
if (/complete|loaded/.test(script.readyState)) {
callback(null, event);
}
});
}
}
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
};
});
require.register("segmentio-script-onload/index.js", function(exports, require, module){
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
/**
* Invoke `fn(err)` when the given `el` script loads.
*
* @param {Element} el
* @param {Function} fn
* @api public
*/
module.exports = function(el, fn){
return el.addEventListener
? add(el, fn)
: attach(el, fn);
};
/**
* Add event listener to `el`, `fn()`.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function add(el, fn){
el.addEventListener('load', function(_, e){ fn(null, e); }, false);
el.addEventListener('error', function(e){
var err = new Error('failed to load the script "' + el.src + '"');
err.event = e;
fn(err);
}, false);
}
/**
* Attach evnet.
*
* @param {Element} el
* @param {Function} fn
* @api private
*/
function attach(el, fn){
el.attachEvent('onreadystatechange', function(e){
if (!/complete|loaded/.test(el.readyState)) return;
fn(null, e);
});
}
});
require.register("segmentio-on-body/index.js", function(exports, require, module){
var each = require('each');
/**
* Cache whether `<body>` exists.
*/
var body = false;
/**
* Callbacks to call when the body exists.
*/
var callbacks = [];
/**
* Export a way to add handlers to be invoked once the body exists.
*
* @param {Function} callback A function to call when the body exists.
*/
module.exports = function onBody (callback) {
if (body) {
call(callback);
} else {
callbacks.push(callback);
}
};
/**
* Set an interval to check for `document.body`.
*/
var interval = setInterval(function () {
if (!document.body) return;
body = true;
each(callbacks, call);
clearInterval(interval);
}, 5);
/**
* Call a callback, passing it the body.
*
* @param {Function} callback The callback to call.
*/
function call (callback) {
callback(document.body);
}
});
require.register("segmentio-on-error/index.js", function(exports, require, module){
/**
* Expose `onError`.
*/
module.exports = onError;
/**
* Callbacks.
*/
var callbacks = [];
/**
* Preserve existing handler.
*/
if ('function' == typeof window.onerror) callbacks.push(window.onerror);
/**
* Bind to `window.onerror`.
*/
window.onerror = handler;
/**
* Error handler.
*/
function handler () {
for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments);
}
/**
* Call a `fn` on `window.onerror`.
*
* @param {Function} fn
*/
function onError (fn) {
callbacks.push(fn);
if (window.onerror != handler) {
callbacks.push(window.onerror);
window.onerror = handler;
}
}
});
require.register("segmentio-to-iso-string/index.js", function(exports, require, module){
/**
* Expose `toIsoString`.
*/
module.exports = toIsoString;
/**
* Turn a `date` into an ISO string.
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @param {Date} date
* @return {String}
*/
function toIsoString (date) {
return date.getUTCFullYear()
+ '-' + pad(date.getUTCMonth() + 1)
+ '-' + pad(date.getUTCDate())
+ 'T' + pad(date.getUTCHours())
+ ':' + pad(date.getUTCMinutes())
+ ':' + pad(date.getUTCSeconds())
+ '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
+ 'Z';
}
/**
* Pad a `number` with a ten's place zero.
*
* @param {Number} number
* @return {String}
*/
function pad (number) {
var n = number.toString();
return n.length === 1 ? '0' + n : n;
}
});
require.register("segmentio-to-unix-timestamp/index.js", function(exports, require, module){
/**
* Expose `toUnixTimestamp`.
*/
module.exports = toUnixTimestamp;
/**
* Convert a `date` into a Unix timestamp.
*
* @param {Date}
* @return {Number}
*/
function toUnixTimestamp (date) {
return Math.floor(date.getTime() / 1000);
}
});
require.register("segmentio-use-https/index.js", function(exports, require, module){
/**
* Protocol.
*/
module.exports = function (url) {
switch (arguments.length) {
case 0: return check();
case 1: return transform(url);
}
};
/**
* Transform a protocol-relative `url` to the use the proper protocol.
*
* @param {String} url
* @return {String}
*/
function transform (url) {
return check() ? 'https:' + url : 'http:' + url;
}
/**
* Check whether `https:` be used for loading scripts.
*
* @return {Boolean}
*/
function check () {
return (
location.protocol == 'https:' ||
location.protocol == 'chrome-extension:'
);
}
});
require.register("segmentio-when/index.js", function(exports, require, module){
var callback = require('callback');
/**
* Expose `when`.
*/
module.exports = when;
/**
* Loop on a short interval until `condition()` is true, then call `fn`.
*
* @param {Function} condition
* @param {Function} fn
* @param {Number} interval (optional)
*/
function when (condition, fn, interval) {
if (condition()) return callback.async(fn);
var ref = setInterval(function () {
if (!condition()) return;
callback(fn);
clearInterval(ref);
}, interval || 10);
}
});
require.register("yields-slug/index.js", function(exports, require, module){
/**
* Generate a slug from the given `str`.
*
* example:
*
* generate('foo bar');
* // > foo-bar
*
* @param {String} str
* @param {Object} options
* @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g`
* @config {String} [separator] separator to insert, defaulted to `-`
* @return {String}
*/
module.exports = function (str, options) {
options || (options = {});
return str.toLowerCase()
.replace(options.replace || /[^a-z0-9]/g, ' ')
.replace(/^ +| +$/g, '')
.replace(/ +/g, options.separator || '-')
};
});
require.register("visionmedia-batch/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
try {
var EventEmitter = require('events').EventEmitter;
} catch (err) {
var Emitter = require('emitter');
}
/**
* Noop.
*/
function noop(){}
/**
* Expose `Batch`.
*/
module.exports = Batch;
/**
* Create a new Batch.
*/
function Batch() {
if (!(this instanceof Batch)) return new Batch;
this.fns = [];
this.concurrency(Infinity);
this.throws(true);
for (var i = 0, len = arguments.length; i < len; ++i) {
this.push(arguments[i]);
}
}
/**
* Inherit from `EventEmitter.prototype`.
*/
if (EventEmitter) {
Batch.prototype.__proto__ = EventEmitter.prototype;
} else {
Emitter(Batch.prototype);
}
/**
* Set concurrency to `n`.
*
* @param {Number} n
* @return {Batch}
* @api public
*/
Batch.prototype.concurrency = function(n){
this.n = n;
return this;
};
/**
* Queue a function.
*
* @param {Function} fn
* @return {Batch}
* @api public
*/
Batch.prototype.push = function(fn){
this.fns.push(fn);
return this;
};
/**
* Set wether Batch will or will not throw up.
*
* @param {Boolean} throws
* @return {Batch}
* @api public
*/
Batch.prototype.throws = function(throws) {
this.e = !!throws;
return this;
};
/**
* Execute all queued functions in parallel,
* executing `cb(err, results)`.
*
* @param {Function} cb
* @return {Batch}
* @api public
*/
Batch.prototype.end = function(cb){
var self = this
, total = this.fns.length
, pending = total
, results = []
, errors = []
, cb = cb || noop
, fns = this.fns
, max = this.n
, throws = this.e
, index = 0
, done;
// empty
if (!fns.length) return cb(null, results);
// process
function next() {
var i = index++;
var fn = fns[i];
if (!fn) return;
var start = new Date;
try {
fn(callback);
} catch (err) {
callback(err);
}
function callback(err, res){
if (done) return;
if (err && throws) return done = true, cb(err);
var complete = total - pending + 1;
var end = new Date;
results[i] = res;
errors[i] = err;
self.emit('progress', {
index: i,
value: res,
error: err,
pending: pending,
total: total,
complete: complete,
percent: complete / total * 100 | 0,
start: start,
end: end,
duration: end - start
});
if (--pending) next()
else if(!throws) cb(errors, results);
else cb(null, results);
}
}
// concurrency
for (var i = 0; i < fns.length; i++) {
if (i == max) break;
next();
}
return this;
};
});
require.register("segmentio-substitute/index.js", function(exports, require, module){
/**
* Expose `substitute`
*/
module.exports = substitute;
/**
* Substitute `:prop` with the given `obj` in `str`
*
* @param {String} str
* @param {Object} obj
* @param {RegExp} expr
* @return {String}
* @api public
*/
function substitute(str, obj, expr){
if (!obj) throw new TypeError('expected an object');
expr = expr || /:(\w+)/g;
return str.replace(expr, function(_, prop){
return null != obj[prop]
? obj[prop]
: _;
});
}
});
require.register("segmentio-load-pixel/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var stringify = require('querystring').stringify;
var sub = require('substitute');
/**
* Factory function to create a pixel loader.
*
* @param {String} path
* @return {Function}
* @api public
*/
module.exports = function(path){
return function(query, obj, fn){
if ('function' == typeof obj) fn = obj, obj = {};
obj = obj || {};
fn = fn || function(){};
var url = sub(path, obj);
var img = new Image;
img.onerror = error(fn, 'failed to load pixel', img);
img.onload = function(){ fn(); };
query = stringify(query);
if (query) query = '?' + query;
img.src = url + query;
img.width = 1;
img.height = 1;
return img;
};
};
/**
* Create an error handler.
*
* @param {Fucntion} fn
* @param {String} message
* @param {Image} img
* @return {Function}
* @api private
*/
function error(fn, message, img){
return function(e){
e = e || window.event;
var err = new Error(message);
err.event = e;
err.source = img;
fn(err);
};
}
});
require.register("segmentio-replace-document-write/index.js", function(exports, require, module){
var domify = require('domify');
/**
* Replace document.write until a url is written matching the url fragment
*
* @param {String} match
* @param {Element} parent to appendChild onto
* @param {Function} fn optional callback function
*/
module.exports = function(match, parent, fn){
var write = document.write;
document.write = append;
if (typeof parent === 'function') fn = parent, parent = null;
if (!parent) parent = document.body;
function append(str){
var el = domify(str)
var src = el.src || '';
if (el.src.indexOf(match) === -1) return write(str);
if ('SCRIPT' == el.tagName) el = recreate(el);
parent.appendChild(el);
document.write = write;
fn && fn();
}
};
/**
* Re-create the given `script`.
*
* domify() actually adds the script to he dom
* and then immediately removes it so the script
* will never be loaded :/
*
* @param {Element} script
* @api public
*/
function recreate(script){
var ret = document.createElement('script');
ret.src = script.src;
ret.async = script.async;
ret.defer = script.defer;
return ret;
}
});
require.register("ianstormtaylor-to-camel-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toCamelCase`.
*/
module.exports = toCamelCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-capital-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toCapitalCase`.
*/
module.exports = toCapitalCase;
/**
* Convert a `string` to capital case.
*
* @param {String} string
* @return {String}
*/
function toCapitalCase (string) {
return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) {
return previous + letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-constant-case/index.js", function(exports, require, module){
var snake = require('to-snake-case');
/**
* Expose `toConstantCase`.
*/
module.exports = toConstantCase;
/**
* Convert a `string` to constant case.
*
* @param {String} string
* @return {String}
*/
function toConstantCase (string) {
return snake(string).toUpperCase();
}
});
require.register("ianstormtaylor-to-dot-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toDotCase`.
*/
module.exports = toDotCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toDotCase (string) {
return toSpace(string).replace(/\s/g, '.');
}
});
require.register("ianstormtaylor-to-pascal-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toPascalCase`.
*/
module.exports = toPascalCase;
/**
* Convert a `string` to pascal case.
*
* @param {String} string
* @return {String}
*/
function toPascalCase (string) {
return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-sentence-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toSentenceCase`.
*/
module.exports = toSentenceCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toSentenceCase (string) {
return clean(string).replace(/[a-z]/i, function (letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-slug-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toSlugCase`.
*/
module.exports = toSlugCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toSlugCase (string) {
return toSpace(string).replace(/\s/g, '-');
}
});
require.register("ianstormtaylor-to-snake-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toSnakeCase`.
*/
module.exports = toSnakeCase;
/**
* Convert a `string` to snake case.
*
* @param {String} string
* @return {String}
*/
function toSnakeCase (string) {
return toSpace(string).replace(/\s/g, '_');
}
});
require.register("ianstormtaylor-to-space-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toSpaceCase`.
*/
module.exports = toSpaceCase;
/**
* Convert a `string` to space case.
*
* @param {String} string
* @return {String}
*/
function toSpaceCase (string) {
return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) {
return match ? ' ' + match : '';
});
}
});
require.register("component-escape-regexp/index.js", function(exports, require, module){
/**
* Escape regexp special characters in `str`.
*
* @param {String} str
* @return {String}
* @api public
*/
module.exports = function(str){
return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1');
};
});
require.register("ianstormtaylor-map/index.js", function(exports, require, module){
var each = require('each');
/**
* Map an array or object.
*
* @param {Array|Object} obj
* @param {Function} iterator
* @return {Mixed}
*/
module.exports = function map (obj, iterator) {
var arr = [];
each(obj, function (o) {
arr.push(iterator.apply(null, arguments));
});
return arr;
};
});
require.register("ianstormtaylor-title-case-minors/index.js", function(exports, require, module){
module.exports = [
'a',
'an',
'and',
'as',
'at',
'but',
'by',
'en',
'for',
'from',
'how',
'if',
'in',
'neither',
'nor',
'of',
'on',
'only',
'onto',
'out',
'or',
'per',
'so',
'than',
'that',
'the',
'to',
'until',
'up',
'upon',
'v',
'v.',
'versus',
'vs',
'vs.',
'via',
'when',
'with',
'without',
'yet'
];
});
require.register("ianstormtaylor-to-title-case/index.js", function(exports, require, module){
var capital = require('to-capital-case')
, escape = require('escape-regexp')
, map = require('map')
, minors = require('title-case-minors');
/**
* Expose `toTitleCase`.
*/
module.exports = toTitleCase;
/**
* Minors.
*/
var escaped = map(minors, escape);
var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig');
var colonMatcher = /:\s*(\w)/g;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toTitleCase (string) {
return capital(string)
.replace(minorMatcher, function (minor) {
return minor.toLowerCase();
})
.replace(colonMatcher, function (letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-case/lib/index.js", function(exports, require, module){
var cases = require('./cases');
/**
* Expose `determineCase`.
*/
module.exports = exports = determineCase;
/**
* Determine the case of a `string`.
*
* @param {String} string
* @return {String|Null}
*/
function determineCase (string) {
for (var key in cases) {
if (key == 'none') continue;
var convert = cases[key];
if (convert(string) == string) return key;
}
return null;
}
/**
* Define a case by `name` with a `convert` function.
*
* @param {String} name
* @param {Object} convert
*/
exports.add = function (name, convert) {
exports[name] = cases[name] = convert;
};
/**
* Add all the `cases`.
*/
for (var key in cases) {
exports.add(key, cases[key]);
}
});
require.register("ianstormtaylor-case/lib/cases.js", function(exports, require, module){
var camel = require('to-camel-case')
, capital = require('to-capital-case')
, constant = require('to-constant-case')
, dot = require('to-dot-case')
, none = require('to-no-case')
, pascal = require('to-pascal-case')
, sentence = require('to-sentence-case')
, slug = require('to-slug-case')
, snake = require('to-snake-case')
, space = require('to-space-case')
, title = require('to-title-case');
/**
* Camel.
*/
exports.camel = camel;
/**
* Pascal.
*/
exports.pascal = pascal;
/**
* Dot. Should precede lowercase.
*/
exports.dot = dot;
/**
* Slug. Should precede lowercase.
*/
exports.slug = slug;
/**
* Snake. Should precede lowercase.
*/
exports.snake = snake;
/**
* Space. Should precede lowercase.
*/
exports.space = space;
/**
* Constant. Should precede uppercase.
*/
exports.constant = constant;
/**
* Capital. Should precede sentence and title.
*/
exports.capital = capital;
/**
* Title.
*/
exports.title = title;
/**
* Sentence.
*/
exports.sentence = sentence;
/**
* Convert a `string` to lower case from camel, slug, etc. Different that the
* usual `toLowerCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.lower = function (string) {
return none(string).toLowerCase();
};
/**
* Convert a `string` to upper case from camel, slug, etc. Different that the
* usual `toUpperCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.upper = function (string) {
return none(string).toUpperCase();
};
/**
* Invert each character in a `string` from upper to lower and vice versa.
*
* @param {String} string
* @return {String}
*/
exports.inverse = function (string) {
for (var i = 0, char; char = string[i]; i++) {
if (!/[a-z]/i.test(char)) continue;
var upper = char.toUpperCase();
var lower = char.toLowerCase();
string[i] = char == upper ? lower : upper;
}
return string;
};
/**
* None.
*/
exports.none = none;
});
require.register("segmentio-obj-case/index.js", function(exports, require, module){
var Case = require('case');
var cases = [
Case.upper,
Case.lower,
Case.snake,
Case.pascal,
Case.camel,
Case.constant,
Case.title,
Case.capital,
Case.sentence
];
/**
* Module exports, export
*/
module.exports = module.exports.find = multiple(find);
/**
* Export the replacement function, return the modified object
*/
module.exports.replace = function (obj, key, val) {
multiple(replace).apply(this, arguments);
return obj;
};
/**
* Export the delete function, return the modified object
*/
module.exports.del = function (obj, key) {
multiple(del).apply(this, arguments);
return obj;
};
/**
* Compose applying the function to a nested key
*/
function multiple (fn) {
return function (obj, key, val) {
var keys = key.split('.');
if (keys.length === 0) return;
while (keys.length > 1) {
key = keys.shift();
obj = find(obj, key);
if (obj === null || obj === undefined) return;
}
key = keys.shift();
return fn(obj, key, val);
};
}
/**
* Find an object by its key
*
* find({ first_name : 'Calvin' }, 'firstName')
*/
function find (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) return obj[cased];
}
}
/**
* Delete a value for a given key
*
* del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' }
*/
function del (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) delete obj[cased];
}
return obj;
}
/**
* Replace an objects existing value with a new one
*
* replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }
*/
function replace (obj, key, val) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) obj[cased] = val;
}
return obj;
}
});
require.register("segmentio-analytics.js-integrations/index.js", function(exports, require, module){
var integrations = require('./lib/slugs');
var each = require('each');
/**
* Expose the integrations, using their own `name` from their `prototype`.
*/
each(integrations, function (slug) {
var plugin = require('./lib/' + slug);
var name = plugin.Integration.prototype.name;
exports[name] = plugin;
});
});
require.register("segmentio-analytics.js-integrations/lib/adroll.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(AdRoll);
user = analytics.user(); // store for later
};
/**
* Expose `AdRoll` integration.
*/
var AdRoll = exports.Integration = integration('AdRoll')
.assumesPageview()
.readyOnLoad()
.global('__adroll_loaded')
.global('adroll_adv_id')
.global('adroll_pix_id')
.global('adroll_custom_data')
.option('events', {})
.option('advId', '')
.option('pixId', '');
/**
* Initialize.
*
* http://support.adroll.com/getting-started-in-4-easy-steps/#step-one
* http://support.adroll.com/enhanced-conversion-tracking/
*
* @param {Object} page
*/
AdRoll.prototype.initialize = function (page) {
window.adroll_adv_id = this.options.advId;
window.adroll_pix_id = this.options.pixId;
if (user.id()) window.adroll_custom_data = { USER_ID: user.id() };
window.__adroll_loaded = true;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
AdRoll.prototype.loaded = function () {
return window.__adroll;
};
/**
* Load the AdRoll library.
*
* @param {Function} callback
*/
AdRoll.prototype.load = function (callback) {
load({
http: 'http://a.adroll.com/j/roundtrip.js',
https: 'https://s.adroll.com/j/roundtrip.js'
}, callback);
};
/**
* Track.
*
* @param {Track} track
*/
AdRoll.prototype.track = function(track){
var events = this.options.events;
var total = track.revenue();
var event = track.event();
if (has.call(events, event)) event = events[event];
window.__adroll.record_user({
adroll_conversion_value_in_dollars: total || 0,
order_id: track.orderId() || 0,
adroll_segments: event
});
};
});
require.register("segmentio-analytics.js-integrations/lib/adwords.js", function(exports, require, module){
var onbody = require('on-body');
var integration = require('integration');
var load = require('load-script');
var domify = require('domify');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(AdWords);
};
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `AdWords`
*/
var AdWords = exports.Integration = integration('AdWords')
.readyOnLoad()
.option('conversionId', '')
.option('events', {});
/**
* Load
*
* @param {Function} fn
* @api public
*/
AdWords.prototype.load = function(fn){
onbody(fn);
};
/**
* Loaded.
*
* @return {Boolean}
* @api public
*/
AdWords.prototype.loaded = function(){
return !! document.body;
};
/**
* Track.
*
* @param {Track}
* @api public
*/
AdWords.prototype.track = function(track){
var id = this.options.conversionId;
var events = this.options.events;
var event = track.event();
if (!has.call(events, event)) return;
return this.conversion({
value: track.revenue() || 0,
label: events[event],
conversionId: id
});
};
/**
* Report AdWords conversion.
*
* @param {Object} globals
* @api private
*/
AdWords.prototype.conversion = function(obj, fn){
if (this.reporting) return this.wait(obj);
this.reporting = true;
this.debug('sending %o', obj);
var self = this;
var write = document.write;
document.write = append;
window.google_conversion_id = obj.conversionId;
window.google_conversion_language = 'en';
window.google_conversion_format = '3';
window.google_conversion_color = 'ffffff';
window.google_conversion_label = obj.label;
window.google_conversion_value = obj.value;
window.google_remarketing_only = false;
load('//www.googleadservices.com/pagead/conversion.js', fn);
function append(str){
var el = domify(str);
if (!el.src) return write(str);
if (!/googleadservices/.test(el.src)) return write(str);
self.debug('append %o', el);
document.body.appendChild(el);
document.write = write;
self.reporting = null;
}
};
/**
* Wait until a conversion is sent with `obj`.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
AdWords.prototype.wait = function(obj){
var self = this;
var id = setTimeout(function(){
clearTimeout(id);
self.conversion(obj);
}, 50);
};
});
require.register("segmentio-analytics.js-integrations/lib/alexa.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Alexa);
};
/**
* Expose Alexa integration.
*/
var Alexa = exports.Integration = integration('Alexa')
.assumesPageview()
.readyOnLoad()
.global('_atrk_opts')
.option('account', null)
.option('domain', '')
.option('dynamic', true);
/**
* Initialize.
*
* @param {Object} page
*/
Alexa.prototype.initialize = function (page) {
window._atrk_opts = {
atrk_acct: this.options.account,
domain: this.options.domain,
dynamic: this.options.dynamic
};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Alexa.prototype.loaded = function () {
return !! window.atrk;
};
/**
* Load the Alexa library.
*
* @param {Function} callback
*/
Alexa.prototype.load = function (callback) {
load('//d31qbv1cthcecs.cloudfront.net/atrk.js', function(err){
if (err) return callback(err);
window.atrk();
callback();
});
};
});
require.register("segmentio-analytics.js-integrations/lib/amplitude.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Amplitude);
};
/**
* Expose `Amplitude` integration.
*/
var Amplitude = exports.Integration = integration('Amplitude')
.assumesPageview()
.readyOnInitialize()
.global('amplitude')
.option('apiKey', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://github.com/amplitude/Amplitude-Javascript
*
* @param {Object} page
*/
Amplitude.prototype.initialize = function (page) {
(function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"]; for(var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document);
window.amplitude.init(this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Amplitude.prototype.loaded = function () {
return !! (window.amplitude && window.amplitude.options);
};
/**
* Load the Amplitude library.
*
* @param {Function} callback
*/
Amplitude.prototype.load = function (callback) {
load('https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Amplitude.prototype.page = function (page) {
var properties = page.properties();
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Identify.
*
* @param {Facade} identify
*/
Amplitude.prototype.identify = function (identify) {
var id = identify.userId();
var traits = identify.traits();
if (id) window.amplitude.setUserId(id);
if (traits) window.amplitude.setGlobalUserProperties(traits);
};
/**
* Track.
*
* @param {Track} event
*/
Amplitude.prototype.track = function (track) {
var props = track.properties();
var event = track.event();
window.amplitude.logEvent(event, props);
};
});
require.register("segmentio-analytics.js-integrations/lib/awesm.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Awesm);
user = analytics.user(); // store for later
};
/**
* Expose `Awesm` integration.
*/
var Awesm = exports.Integration = integration('awe.sm')
.assumesPageview()
.readyOnLoad()
.global('AWESM')
.option('apiKey', '')
.option('events', {});
/**
* Initialize.
*
* http://developers.awe.sm/guides/javascript/
*
* @param {Object} page
*/
Awesm.prototype.initialize = function (page) {
window.AWESM = { api_key: this.options.apiKey };
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesm.prototype.loaded = function () {
return !! window.AWESM._exists;
};
/**
* Load.
*
* @param {Function} callback
*/
Awesm.prototype.load = function (callback) {
var key = this.options.apiKey;
load('//widgets.awe.sm/v3/widgets.js?key=' + key + '&async=true', callback);
};
/**
* Track.
*
* @param {Track} track
*/
Awesm.prototype.track = function (track) {
var event = track.event();
var goal = this.options.events[event];
if (!goal) return;
window.AWESM.convert(goal, track.cents(), null, user.id());
};
});
require.register("segmentio-analytics.js-integrations/lib/awesomatic.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var noop = function(){};
var onBody = require('on-body');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Awesomatic);
user = analytics.user(); // store for later
};
/**
* Expose `Awesomatic` integration.
*/
var Awesomatic = exports.Integration = integration('Awesomatic')
.assumesPageview()
.global('Awesomatic')
.global('AwesomaticSettings')
.global('AwsmSetup')
.global('AwsmTmp')
.option('appId', '');
/**
* Initialize.
*
* @param {Object} page
*/
Awesomatic.prototype.initialize = function (page) {
var self = this;
var id = user.id();
var options = user.traits();
options.appId = this.options.appId;
if (id) options.user_id = id;
this.load(function () {
window.Awesomatic.initialize(options, function () {
self.emit('ready'); // need to wait for initialize to callback
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesomatic.prototype.loaded = function () {
return is.object(window.Awesomatic);
};
/**
* Load the Awesomatic library.
*
* @param {Function} callback
*/
Awesomatic.prototype.load = function (callback) {
var url = 'https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js';
load(url, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/bing-ads.js", function(exports, require, module){
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Bing);
};
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Bing`
*/
var Bing = exports.Integration = integration('Bing Ads')
.readyOnInitialize()
.option('siteId', '')
.option('domainId', '')
.option('goals', {});
/**
* Track.
*
* @param {Track} track
*/
Bing.prototype.track = function(track){
var goals = this.options.goals;
var traits = track.traits();
var event = track.event();
if (!has.call(goals, event)) return;
var goal = goals[event];
return exports.load(goal, track.revenue(), this.options);
};
/**
* Load conversion.
*
* @param {Mixed} goal
* @param {Number} revenue
* @param {String} currency
* @return {IFrame}
* @api private
*/
exports.load = function(goal, revenue, options){
var iframe = document.createElement('iframe');
iframe.src = '//flex.msn.com/mstag/tag/' + options.siteId
+ '/analytics.html'
+ '?domainId=' + options.domainId
+ '&revenue=' + revenue || 0
+ '&actionid=' + goal;
+ '&dedup=1'
+ '&type=1'
iframe.width = 1;
iframe.height = 1;
return iframe;
};
});
require.register("segmentio-analytics.js-integrations/lib/bronto.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var Track = require('facade').Track;
var load = require('load-script');
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Bronto);
};
/**
* Expose `Bronto` integration.
*/
var Bronto = exports.Integration = integration('Bronto')
.readyOnLoad()
.global('__bta')
.option('siteId', '')
.option('host', '');
/**
* Initialize.
*
* http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB
* http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB
*
* @param {Object} page
*/
Bronto.prototype.initialize = function(page){
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bronto.prototype.loaded = function(){
return this.bta;
};
/**
* Load the Bronto library.
*
* @param {Function} fn
*/
Bronto.prototype.load = function(fn){
var self = this;
load('//p.bm23.com/bta.js', function(err){
if (err) return fn(err);
var opts = self.options;
self.bta = new window.__bta(opts.siteId);
if (opts.host) self.bta.setHost(opts.host);
fn();
});
};
/**
* Track.
*
* @param {Track} event
*/
Bronto.prototype.track = function(track){
var revenue = track.revenue();
var event = track.event();
var type = 'number' == typeof revenue ? '$' : 't';
this.bta.addConversionLegacy(type, event, revenue);
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
Bronto.prototype.completedOrder = function(track){
var products = track.products();
var props = track.properties();
var items = [];
// items
each(products, function(product){
var track = new Track({ properties: product });
items.push({
item_id: track.id() || track.sku(),
desc: product.description || track.name(),
quantity: track.quantity(),
amount: track.price(),
});
});
// add conversion
this.bta.addConversion({
order_id: track.orderId(),
date: props.date || new Date,
items: items
});
};
});
require.register("segmentio-analytics.js-integrations/lib/bugherd.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(BugHerd);
};
/**
* Expose `BugHerd` integration.
*/
var BugHerd = exports.Integration = integration('BugHerd')
.assumesPageview()
.readyOnLoad()
.global('BugHerdConfig')
.global('_bugHerd')
.option('apiKey', '')
.option('showFeedbackTab', true);
/**
* Initialize.
*
* http://support.bugherd.com/home
*
* @param {Object} page
*/
BugHerd.prototype.initialize = function (page) {
window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
BugHerd.prototype.loaded = function () {
return !! window._bugHerd;
};
/**
* Load the BugHerd library.
*
* @param {Function} callback
*/
BugHerd.prototype.load = function (callback) {
load('//www.bugherd.com/sidebarv2.js?apikey=' + this.options.apiKey, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/bugsnag.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var extend = require('extend');
var load = require('load-script');
var onError = require('on-error');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Bugsnag);
};
/**
* Expose `Bugsnag` integration.
*/
var Bugsnag = exports.Integration = integration('Bugsnag')
.readyOnLoad()
.global('Bugsnag')
.option('apiKey', '');
/**
* Initialize.
*
* https://bugsnag.com/docs/notifiers/js
*
* @param {Object} page
*/
Bugsnag.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bugsnag.prototype.loaded = function () {
return is.object(window.Bugsnag);
};
/**
* Load.
*
* @param {Function} callback (optional)
*/
Bugsnag.prototype.load = function (callback) {
var apiKey = this.options.apiKey;
load('//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js', function(err){
if (err) return callback(err);
window.Bugsnag.apiKey = apiKey;
callback();
});
};
/**
* Identify.
*
* @param {Identify} identify
*/
Bugsnag.prototype.identify = function (identify) {
window.Bugsnag.metaData = window.Bugsnag.metaData || {};
extend(window.Bugsnag.metaData, identify.traits());
};
});
require.register("segmentio-analytics.js-integrations/lib/chartbeat.js", function(exports, require, module){
var integration = require('integration');
var onBody = require('on-body');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Chartbeat);
};
/**
* Expose `Chartbeat` integration.
*/
var Chartbeat = exports.Integration = integration('Chartbeat')
.assumesPageview()
.readyOnLoad()
.global('_sf_async_config')
.global('_sf_endpt')
.global('pSUPERFLY')
.option('domain', '')
.option('uid', null);
/**
* Initialize.
*
* http://chartbeat.com/docs/configuration_variables/
*
* @param {Object} page
*/
Chartbeat.prototype.initialize = function (page) {
window._sf_async_config = this.options;
onBody(function () {
window._sf_endpt = new Date().getTime();
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Chartbeat.prototype.loaded = function () {
return !! window.pSUPERFLY;
};
/**
* Load the Chartbeat library.
*
* http://chartbeat.com/docs/adding_the_code/
*
* @param {Function} callback
*/
Chartbeat.prototype.load = function (callback) {
load({
https: 'https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js',
http: 'http://static.chartbeat.com/js/chartbeat.js'
}, callback);
};
/**
* Page.
*
* http://chartbeat.com/docs/handling_virtual_page_changes/
*
* @param {Page} page
*/
Chartbeat.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
window.pSUPERFLY.virtualPage(props.path, name || props.title);
};
});
require.register("segmentio-analytics.js-integrations/lib/churnbee.js", function(exports, require, module){
/**
* Module dependencies.
*/
var push = require('global-queue')('_cbq');
var integration = require('integration');
var load = require('load-script');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Supported events
*/
var supported = {
activation: true,
changePlan: true,
register: true,
refund: true,
charge: true,
cancel: true,
login: true
};
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(ChurnBee);
};
/**
* Expose `ChurnBee` integration.
*/
var ChurnBee = exports.Integration = integration('ChurnBee')
.readyOnInitialize()
.global('_cbq')
.global('ChurnBee')
.option('events', {})
.option('apiKey', '');
/**
* Initialize.
*
* https://churnbee.com/docs
*
* @param {Object} page
*/
ChurnBee.prototype.initialize = function(page){
push('_setApiKey', this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
ChurnBee.prototype.loaded = function(){
return !! window.ChurnBee;
};
/**
* Load the ChurnBee library.
*
* @param {Function} fn
*/
ChurnBee.prototype.load = function(fn){
load('//api.churnbee.com/cb.js', fn);
};
/**
* Track.
*
* @param {Track} event
*/
ChurnBee.prototype.track = function(track){
var events = this.options.events;
var event = track.event();
if (has.call(events, event)) event = events[event];
if (true != supported[event]) return;
push(event, track.properties({ revenue: 'amount' }));
};
});
require.register("segmentio-analytics.js-integrations/lib/clicktale.js", function(exports, require, module){
var date = require('load-date');
var domify = require('domify');
var each = require('each');
var integration = require('integration');
var is = require('is');
var useHttps = require('use-https');
var load = require('load-script');
var onBody = require('on-body');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(ClickTale);
};
/**
* Expose `ClickTale` integration.
*/
var ClickTale = exports.Integration = integration('ClickTale')
.assumesPageview()
.readyOnLoad()
.global('WRInitTime')
.global('ClickTale')
.global('ClickTaleSetUID')
.global('ClickTaleField')
.global('ClickTaleEvent')
.option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js')
.option('httpsCdnUrl', '')
.option('projectId', '')
.option('recordingRatio', 0.01)
.option('partitionId', '');
/**
* Initialize.
*
* http://wiki.clicktale.com/Article/JavaScript_API
*
* @param {Object} page
*/
ClickTale.prototype.initialize = function (page) {
var options = this.options;
window.WRInitTime = date.getTime();
onBody(function (body) {
body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'));
});
this.load(function () {
window.ClickTale(options.projectId, options.recordingRatio, options.partitionId);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
ClickTale.prototype.loaded = function () {
return is.fn(window.ClickTale);
};
/**
* Load the ClickTale library.
*
* @param {Function} callback
*/
ClickTale.prototype.load = function (callback) {
var http = this.options.httpCdnUrl;
var https = this.options.httpsCdnUrl;
if (useHttps() && !https) return this.debug('https option required');
load({ http: http, https: https }, callback);
};
/**
* Identify.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField
*
* @param {Identify} identify
*/
ClickTale.prototype.identify = function (identify) {
var id = identify.userId();
window.ClickTaleSetUID(id);
each(identify.traits(), function (key, value) {
window.ClickTaleField(key, value);
});
};
/**
* Track.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent
*
* @param {Track} track
*/
ClickTale.prototype.track = function (track) {
window.ClickTaleEvent(track.event());
};
});
require.register("segmentio-analytics.js-integrations/lib/clicky.js", function(exports, require, module){
var Identify = require('facade').Identify;
var extend = require('extend');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Clicky);
user = analytics.user(); // store for later
};
/**
* Expose `Clicky` integration.
*/
var Clicky = exports.Integration = integration('Clicky')
.assumesPageview()
.readyOnLoad()
.global('clicky')
.global('clicky_site_ids')
.global('clicky_custom')
.option('siteId', null);
/**
* Initialize.
*
* http://clicky.com/help/customization
*
* @param {Object} page
*/
Clicky.prototype.initialize = function (page) {
window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId];
this.identify(new Identify({
userId: user.id(),
traits: user.traits()
}));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Clicky.prototype.loaded = function () {
return is.object(window.clicky);
};
/**
* Load the Clicky library.
*
* @param {Function} callback
*/
Clicky.prototype.load = function (callback) {
load('//static.getclicky.com/js', callback);
};
/**
* Page.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Page} page
*/
Clicky.prototype.page = function (page) {
var properties = page.properties();
var category = page.category();
var name = page.fullName();
window.clicky.log(properties.path, name || properties.title);
};
/**
* Identify.
*
* @param {Identify} id (optional)
*/
Clicky.prototype.identify = function (identify) {
window.clicky_custom = window.clicky_custom || {};
window.clicky_custom.session = window.clicky_custom.session || {};
extend(window.clicky_custom.session, identify.traits());
};
/**
* Track.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Track} event
*/
Clicky.prototype.track = function (track) {
window.clicky.goal(track.event(), track.revenue());
};
});
require.register("segmentio-analytics.js-integrations/lib/comscore.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Comscore);
};
/**
* Expose `Comscore` integration.
*/
var Comscore = exports.Integration = integration('comScore')
.assumesPageview()
.readyOnLoad()
.global('_comscore')
.global('COMSCORE')
.option('c1', '2')
.option('c2', '');
/**
* Initialize.
*
* @param {Object} page
*/
Comscore.prototype.initialize = function (page) {
window._comscore = window._comscore || [this.options];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Comscore.prototype.loaded = function () {
return !! window.COMSCORE;
};
/**
* Load.
*
* @param {Function} callback
*/
Comscore.prototype.load = function (callback) {
load({
http: 'http://b.scorecardresearch.com/beacon.js',
https: 'https://sb.scorecardresearch.com/beacon.js'
}, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(CrazyEgg);
};
/**
* Expose `CrazyEgg` integration.
*/
var CrazyEgg = exports.Integration = integration('Crazy Egg')
.assumesPageview()
.readyOnLoad()
.global('CE2')
.option('accountNumber', '');
/**
* Initialize.
*
* @param {Object} page
*/
CrazyEgg.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
CrazyEgg.prototype.loaded = function () {
return !! window.CE2;
};
/**
* Load the Crazy Egg library.
*
* @param {Function} callback
*/
CrazyEgg.prototype.load = function (callback) {
var number = this.options.accountNumber;
var path = number.slice(0,4) + '/' + number.slice(4);
var cache = Math.floor(new Date().getTime()/3600000);
var url = '//dnn506yrbagrg.cloudfront.net/pages/scripts/' + path + '.js?' + cache;
load(url, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/curebit.js", function(exports, require, module){
var clone = require('clone');
var each = require('each');
var Identify = require('facade').Identify;
var integration = require('integration');
var iso = require('to-iso-string');
var load = require('load-script');
var push = require('global-queue')('_curebitq');
var Track = require('facade').Track;
/**
* User reference
*/
var user;
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Curebit);
user = analytics.user();
};
/**
* Expose `Curebit` integration
*/
var Curebit = exports.Integration = integration('Curebit')
.readyOnInitialize()
.global('_curebitq')
.global('curebit')
.option('siteId', '')
.option('iframeWidth', '100%')
.option('iframeHeight', '480')
.option('iframeBorder', 0)
.option('iframeId', '')
.option('responsive', true)
.option('device', '')
.option('insertIntoId', 'curebit-frame')
.option('campaigns', {})
.option('server', 'https://www.curebit.com');
/**
* Initialize.
*
* @param {Object} page
*/
Curebit.prototype.initialize = function(page){
push('init', {
site_id: this.options.siteId,
server: this.options.server
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Curebit.prototype.loaded = function(){
return !! window.curebit;
};
/**
* Load Curebit's Javascript library.
*
* @param {Function} fn
*/
Curebit.prototype.load = function(fn){
var url = '//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js';
load(url, fn);
};
/**
* Page.
*
* Call the `register_affiliate` method of the Curebit API that will load a
* custom iframe onto the page, only if this page's path is marked as a
* campaign.
*
* http://www.curebit.com/docs/affiliate/registration
*
* @param {Page} page
*/
Curebit.prototype.page = function(page){
var campaigns = this.options.campaigns;
var path = window.location.pathname;
if (!campaigns[path]) return;
var tags = (campaigns[path] || '').split(',');
if (!tags.length) return;
var settings = {
responsive: this.options.responsive,
device: this.options.device,
campaign_tags: tags,
iframe: {
width: this.options.iframeWidth,
height: this.options.iframeHeight,
id: this.options.iframeId,
frameborder: this.options.iframeBorder,
container: this.options.insertIntoId
}
};
var identify = new Identify({
userId: user.id(),
traits: user.traits()
});
// if we have an email, add any information about the user
if (identify.email()) {
settings.affiliate_member = {
email: identify.email(),
first_name: identify.firstName(),
last_name: identify.lastName(),
customer_id: identify.userId()
};
}
push('register_affiliate', settings);
};
/**
* Completed order.
*
* Fire the Curebit `register_purchase` with the order details and items.
*
* https://www.curebit.com/docs/ecommerce/custom
*
* @param {Track} track
*/
Curebit.prototype.completedOrder = function(track){
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
var items = [];
var identify = new Identify({
traits: user.traits(),
userId: user.id()
});
each(products, function(product){
var track = new Track({ properties: product });
items.push({
product_id: track.id() || track.sku(),
quantity: track.quantity(),
image_url: product.image,
price: track.price(),
title: track.name(),
url: product.url,
});
});
push('register_purchase', {
order_date: iso(props.date || new Date),
order_number: orderId,
coupon_code: track.coupon(),
subtotal: track.total(),
customer_id: identify.userId(),
first_name: identify.firstName(),
last_name: identify.lastName(),
email: identify.email(),
items: items
});
};
});
require.register("segmentio-analytics.js-integrations/lib/customerio.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var Identify = require('facade').Identify;
var integration = require('integration');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Customerio);
user = analytics.user(); // store for later
};
/**
* Expose `Customerio` integration.
*/
var Customerio = exports.Integration = integration('Customer.io')
.assumesPageview()
.readyOnInitialize()
.global('_cio')
.option('siteId', '');
/**
* Initialize.
*
* http://customer.io/docs/api/javascript.html
*
* @param {Object} page
*/
Customerio.prototype.initialize = function (page) {
window._cio = window._cio || [];
(function() {var a,b,c; a = function (f) {return function () {window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })();
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Customerio.prototype.loaded = function () {
return !! (window._cio && window._cio.pageHasLoaded);
};
/**
* Load.
*
* @param {Function} callback
*/
Customerio.prototype.load = function (callback) {
var script = load('https://assets.customer.io/assets/track.js', callback);
script.id = 'cio-tracker';
script.setAttribute('data-site-id', this.options.siteId);
};
/**
* Identify.
*
* http://customer.io/docs/api/javascript.html#section-Identify_customers
*
* @param {Identify} identify
*/
Customerio.prototype.identify = function (identify) {
if (!identify.userId()) return this.debug('user id required');
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
window._cio.identify(traits);
};
/**
* Group.
*
* @param {Group} group
*/
Customerio.prototype.group = function (group) {
var traits = group.traits();
traits = alias(traits, function (trait) {
return 'Group ' + trait;
});
this.identify(new Identify({
userId: user.id(),
traits: traits
}));
};
/**
* Track.
*
* http://customer.io/docs/api/javascript.html#section-Track_a_custom_event
*
* @param {Track} track
*/
Customerio.prototype.track = function (track) {
var properties = track.properties();
properties = convertDates(properties, convertDate);
window._cio.track(track.event(), properties);
};
/**
* Convert a date to the format Customer.io supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate (date) {
return Math.floor(date.getTime() / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/drip.js", function(exports, require, module){
var alias = require('alias');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_dcq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Drip);
};
/**
* Expose `Drip` integration.
*/
var Drip = exports.Integration = integration('Drip')
.assumesPageview()
.readyOnLoad()
.global('dc')
.global('_dcq')
.global('_dcs')
.option('account', '');
/**
* Initialize.
*
* @param {Object} page
*/
Drip.prototype.initialize = function (page) {
window._dcq = window._dcq || [];
window._dcs = window._dcs || {};
window._dcs.account = this.options.account;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Drip.prototype.loaded = function () {
return is.object(window.dc);
};
/**
* Load.
*
* @param {Function} callback
*/
Drip.prototype.load = function (callback) {
load('//tag.getdrip.com/' + this.options.account + '.js', callback);
};
/**
* Track.
*
* @param {Track} track
*/
Drip.prototype.track = function (track) {
var props = track.properties();
var cents = Math.round(track.cents());
props.action = track.event();
if (cents) props.value = cents;
delete props.revenue;
push('track', props);
};
});
require.register("segmentio-analytics.js-integrations/lib/errorception.js", function(exports, require, module){
var callback = require('callback');
var extend = require('extend');
var integration = require('integration');
var load = require('load-script');
var onError = require('on-error');
var push = require('global-queue')('_errs');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Errorception);
};
/**
* Expose `Errorception` integration.
*/
var Errorception = exports.Integration = integration('Errorception')
.assumesPageview()
.readyOnInitialize()
.global('_errs')
.option('projectId', '')
.option('meta', true);
/**
* Initialize.
*
* https://github.com/amplitude/Errorception-Javascript
*
* @param {Object} page
*/
Errorception.prototype.initialize = function (page) {
window._errs = window._errs || [this.options.projectId];
onError(push);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Errorception.prototype.loaded = function () {
return !! (window._errs && window._errs.push !== Array.prototype.push);
};
/**
* Load the Errorception library.
*
* @param {Function} callback
*/
Errorception.prototype.load = function (callback) {
load('//beacon.errorception.com/' + this.options.projectId + '.js', callback);
};
/**
* Identify.
*
* http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html
*
* @param {Object} identify
*/
Errorception.prototype.identify = function (identify) {
if (!this.options.meta) return;
var traits = identify.traits();
window._errs = window._errs || [];
window._errs.meta = window._errs.meta || {};
extend(window._errs.meta, traits);
};
});
require.register("segmentio-analytics.js-integrations/lib/evergage.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_aaq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Evergage);
};
/**
* Expose `Evergage` integration.integration.
*/
var Evergage = exports.Integration = integration('Evergage')
.assumesPageview()
.readyOnInitialize()
.global('_aaq')
.option('account', '')
.option('dataset', '');
/**
* Initialize.
*
* @param {Object} page
*/
Evergage.prototype.initialize = function (page) {
var account = this.options.account;
var dataset = this.options.dataset;
window._aaq = window._aaq || [];
push('setEvergageAccount', account);
push('setDataset', dataset);
push('setUseSiteConfig', true);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Evergage.prototype.loaded = function () {
return !! (window._aaq && window._aaq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Evergage.prototype.load = function (callback) {
var account = this.options.account;
var dataset = this.options.dataset;
var url = '//cdn.evergage.com/beacon/' + account + '/' + dataset + '/scripts/evergage.min.js';
load(url, callback);
};
/**
* Page.
*
* @param {Page} page
*/
Evergage.prototype.page = function (page) {
var props = page.properties();
var name = page.name();
if (name) push('namePage', name);
each(props, function(key, value) {
push('setCustomField', key, value, 'page');
});
window.Evergage.init(true);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Evergage.prototype.identify = function (identify) {
var id = identify.userId();
if (!id) return;
push('setUser', id);
var traits = identify.traits({
email: 'userEmail',
name: 'userName'
});;
each(traits, function (key, value) {
push('setUserField', key, value, 'page');
});
};
/**
* Group.
*
* @param {Group} group
*/
Evergage.prototype.group = function (group) {
var props = group.traits();
var id = group.groupId();
if (!id) return;
push('setCompany', id);
each(props, function(key, value) {
push('setAccountField', key, value, 'page');
});
};
/**
* Track.
*
* @param {Track} track
*/
Evergage.prototype.track = function (track) {
push('trackAction', track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js", function(exports, require, module){
var load = require('load-pixel')('//www.facebook.com/offsite_event.php');
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Facebook);
};
/**
* Expose `load`.
*/
exports.load = load;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Facebook`
*/
var Facebook = exports.Integration = integration('Facebook Ads')
.readyOnInitialize()
.option('currency', 'USD')
.option('events', {});
/**
* Track.
*
* @param {Track} track
*/
Facebook.prototype.track = function(track){
var events = this.options.events;
var traits = track.traits();
var event = track.event();
if (!has.call(events, event)) return;
return exports.load({
currency: this.options.currency,
value: track.revenue() || 0,
id: events[event]
});
};
});
require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js", function(exports, require, module){
var push = require('global-queue')('_fxm');
var integration = require('integration');
var Track = require('facade').Track;
var callback = require('callback');
var load = require('load-script');
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(FoxMetrics);
};
/**
* Expose `FoxMetrics` integration.
*/
var FoxMetrics = exports.Integration = integration('FoxMetrics')
.assumesPageview()
.readyOnInitialize()
.global('_fxm')
.option('appId', '');
/**
* Initialize.
*
* http://foxmetrics.com/documentation/apijavascript
*
* @param {Object} page
*/
FoxMetrics.prototype.initialize = function(page){
window._fxm = window._fxm || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
FoxMetrics.prototype.loaded = function(){
return !! (window._fxm && window._fxm.appId);
};
/**
* Load the FoxMetrics library.
*
* @param {Function} callback
*/
FoxMetrics.prototype.load = function(callback){
var id = this.options.appId;
load('//d35tca7vmefkrc.cloudfront.net/scripts/' + id + '.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
FoxMetrics.prototype.page = function(page){
var properties = page.proxy('properties');
var category = page.category();
var name = page.name();
this._category = category; // store for later
push(
'_fxm.pages.view',
properties.title, // title
name, // name
category, // category
properties.url, // url
properties.referrer // referrer
);
};
/**
* Identify.
*
* @param {Identify} identify
*/
FoxMetrics.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
push(
'_fxm.visitor.profile',
id, // user id
identify.firstName(), // first name
identify.lastName(), // last name
identify.email(), // email
identify.address(), // address
undefined, // social
undefined, // partners
identify.traits() // attributes
);
};
/**
* Track.
*
* @param {Track} track
*/
FoxMetrics.prototype.track = function(track){
var props = track.properties();
var category = this._category || props.category;
push(track.event(), category, props);
};
/**
* Viewed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.viewedProduct = function(track){
ecommerce('productview', track);
};
/**
* Removed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.removedProduct = function(track){
ecommerce('removecartitem', track);
};
/**
* Added product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.addedProduct = function(track){
ecommerce('cartitem', track);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.completedOrder = function(track){
var orderId = track.orderId();
// transaction
push('_fxm.ecommerce.order'
, orderId
, track.subtotal()
, track.shipping()
, track.tax()
, track.city()
, track.state()
, track.zip()
, track.quantity());
// items
each(track.products(), function(product){
var track = new Track({ properties: product });
ecommerce('purchaseitem', track, [
track.quantity(),
track.price(),
orderId
]);
});
};
/**
* Track ecommerce `event` with `track`
* with optional `arr` to append.
*
* @param {String} event
* @param {Track} track
* @param {Array} arr
* @api private
*/
function ecommerce(event, track, arr){
push.apply(null, [
'_fxm.ecommerce.' + event,
track.id() || track.sku(),
track.name(),
track.category()
].concat(arr || []));
};
});
require.register("segmentio-analytics.js-integrations/lib/frontleaf.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Frontleaf);
};
/**
* Expose `Frontleaf` integration.
*/
var Frontleaf = exports.Integration = integration('Frontleaf')
.assumesPageview()
.readyOnInitialize()
.global('_fl')
.global('_flBaseUrl')
.option('baseUrl', 'https://api.frontleaf.com')
.option('token', '')
.option('stream', '');
/**
* Initialize.
*
* http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon
*
* @param {Object} page
*/
Frontleaf.prototype.initialize = function (page) {
window._fl = window._fl || [];
window._flBaseUrl = window._flBaseUrl || this.options.baseUrl;
this._push('setApiToken', this.options.token);
this._push('setStream', this.options.stream);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Frontleaf.prototype.loaded = function () {
return is.array(window._fl) && window._fl.ready === true ;
};
/**
* Load.
*
* @param {Function} fn
*/
Frontleaf.prototype.load = function (fn) {
if (document.getElementById('_fl')) return callback.async(fn);
var script = load(window._flBaseUrl + '/lib/tracker.js', fn);
script.id = '_fl';
};
/**
* Identify.
*
* @param {Identify} identify
*/
Frontleaf.prototype.identify = function (identify) {
var userId = identify.userId();
if (userId) {
this._push('setUser', {
id : userId,
name : identify.name() || identify.username(),
data : clean(identify.traits())
});
}
};
/**
* Group.
*
* @param {Group} group
*/
Frontleaf.prototype.group = function (group) {
var groupId = group.groupId();
if (groupId) {
this._push('setAccount', {
id : groupId,
name : group.proxy('traits.name'),
data : clean(group.traits())
});
}
};
/**
* Track.
*
* @param {Track} track
*/
Frontleaf.prototype.track = function (track) {
var event = track.event();
if (event) {
this._push('event', event, clean(track.properties()));
}
};
/**
* Push a command onto the global Frontleaf queue.
*
* @param {String} command
* @return {Object} args
* @api private
*/
Frontleaf.prototype._push = function (command) {
var args = [].slice.call(arguments, 1);
window._fl.push(function(t) { t[command].apply(command, args); });
}
/**
* Clean all nested objects and arrays.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function clean(obj) {
var ret = {};
// Remove traits/properties that are already represented
// outside of the data container
var excludeKeys = ["id","name","firstName","lastName"];
var len = excludeKeys.length;
for (var i = 0; i < len; i++) {
clear(obj, excludeKeys[i]);
}
// Flatten nested hierarchy, preserving arrays
obj = flatten(obj);
// Discard nulls, represent arrays as comma-separated strings
for (var key in obj) {
var val = obj[key];
if (null == val) {
continue;
}
if (is.array(val)) {
ret[key] = val.toString();
continue;
}
ret[key] = val;
}
return ret;
}
/**
* Remove a property from an object if set.
*
* @param {Object} obj
* @param {String} key
* @api private
*/
function clear(obj, key) {
if (obj.hasOwnProperty(key)) {
delete obj[key];
}
}
/**
* Flatten a nested object into a single level space-delimited
* hierarchy.
*
* Based on https://github.com/hughsk/flat
*
* @param {Object} source
* @return {Object}
* @api private
*/
function flatten(source) {
var output = {};
function step(object, prev) {
for (var key in object) {
var value = object[key];
var newKey = prev ? prev + ' ' + key : key;
if (!is.array(value) && is.object(value)) {
return step(value, newKey);
}
output[newKey] = value;
}
}
step(source);
return output;
}
});
require.register("segmentio-analytics.js-integrations/lib/gauges.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_gauges');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Gauges);
};
/**
* Expose `Gauges` integration.
*/
var Gauges = exports.Integration = integration('Gauges')
.assumesPageview()
.readyOnInitialize()
.global('_gauges')
.option('siteId', '');
/**
* Initialize Gauges.
*
* http://get.gaug.es/documentation/tracking/
*
* @param {Object} page
*/
Gauges.prototype.initialize = function (page) {
window._gauges = window._gauges || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Gauges.prototype.loaded = function () {
return !! (window._gauges && window._gauges.push !== Array.prototype.push);
};
/**
* Load the Gauges library.
*
* @param {Function} callback
*/
Gauges.prototype.load = function (callback) {
var id = this.options.siteId;
var script = load('//secure.gaug.es/track.js', callback);
script.id = 'gauges-tracker';
script.setAttribute('data-site-id', id);
};
/**
* Page.
*
* @param {Page} page
*/
Gauges.prototype.page = function (page) {
push('track');
};
});
require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var onBody = require('on-body');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GetSatisfaction);
};
/**
* Expose `GetSatisfaction` integration.
*/
var GetSatisfaction = exports.Integration = integration('Get Satisfaction')
.assumesPageview()
.readyOnLoad()
.global('GSFN')
.option('widgetId', '');
/**
* Initialize.
*
* https://console.getsatisfaction.com/start/101022?signup=true#engage
*
* @param {Object} page
*/
GetSatisfaction.prototype.initialize = function (page) {
var widget = this.options.widgetId;
var div = document.createElement('div');
var id = div.id = 'getsat-widget-' + widget;
onBody(function (body) { body.appendChild(div); });
// usually the snippet is sync, so wait for it before initializing the tab
this.load(function () {
window.GSFN.loadWidget(widget, { containerId: id });
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
GetSatisfaction.prototype.loaded = function () {
return !! window.GSFN;
};
/**
* Load the Get Satisfaction library.
*
* @param {Function} callback
*/
GetSatisfaction.prototype.load = function (callback) {
load('https://loader.engage.gsfn.us/loader.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/google-analytics.js", function(exports, require, module){
var callback = require('callback');
var canonical = require('canonical');
var each = require('each');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_gaq');
var Track = require('facade').Track;
var length = require('object').length;
var keys = require('object').keys;
var dot = require('obj-case');
var type = require('type');
var url = require('url');
var group;
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GA);
group = analytics.group();
user = analytics.user();
};
/**
* Expose `GA` integration.
*
* http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate
*/
var GA = exports.Integration = integration('Google Analytics')
.readyOnLoad()
.global('ga')
.global('gaplugins')
.global('_gaq')
.global('GoogleAnalyticsObject')
.option('anonymizeIp', false)
.option('classic', false)
.option('domain', 'none')
.option('doubleClick', false)
.option('enhancedLinkAttribution', false)
.option('ignoredReferrers', null)
.option('includeSearch', false)
.option('siteSpeedSampleRate', null)
.option('trackingId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('sendUserId', false)
.option('metrics', {})
.option('dimensions', {});
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
GA.on('construct', function (integration) {
if (!integration.options.classic) return;
integration.initialize = integration.initializeClassic;
integration.load = integration.loadClassic;
integration.loaded = integration.loadedClassic;
integration.page = integration.pageClassic;
integration.track = integration.trackClassic;
integration.completedOrder = integration.completedOrderClassic;
});
/**
* Initialize.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced
*/
GA.prototype.initialize = function () {
var opts = this.options;
var gMetrics = metrics(group.traits(), opts);
var uMetrics = metrics(user.traits(), opts);
var custom;
// setup the tracker globals
window.GoogleAnalyticsObject = 'ga';
window.ga = window.ga || function () {
window.ga.q = window.ga.q || [];
window.ga.q.push(arguments);
};
window.ga.l = new Date().getTime();
window.ga('create', opts.trackingId, {
cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string
siteSpeedSampleRate: opts.siteSpeedSampleRate,
allowLinker: true
});
// display advertising
if (opts.doubleClick) {
window.ga('require', 'displayfeatures');
}
// send global id
if (opts.sendUserId && user.id()) {
window.ga('set', '&uid', user.id());
}
// anonymize after initializing, otherwise a warning is shown
// in google analytics debugger
if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true);
// custom dimensions & metrics
if (length(gMetrics)) window.ga('set', gMetrics);
if (length(uMetrics)) window.ga('set', uMetrics);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
GA.prototype.loaded = function () {
return !! window.gaplugins;
};
/**
* Load the Google Analytics library.
*
* @param {Function} callback
*/
GA.prototype.load = function (callback) {
load('//www.google-analytics.com/analytics.js', callback);
};
/**
* Page.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
*
* @param {Page} page
*/
GA.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
var pageview = {};
var track;
this._category = category; // store for later
// add metrics and dimensions
var hit = metrics(page.properties(), this.options);
hit.page = path(props, this.options);
hit.title = name || props.title;
hit.location = props.url;
// send
window.ga('send', 'pageview', hit);
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/events
* https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference
*
* @param {Track} event
*/
GA.prototype.track = function (track, options) {
var opts = options || track.options(this.name);
var props = track.properties();
// metrics & dimensions
var event = metrics(props, this.options);
// event
event.eventAction = track.event();
event.eventCategory = this._category || props.category || 'All';
event.eventLabel = props.label;
event.eventValue = formatValue(props.value || track.revenue());
event.nonInteraction = props.noninteraction || opts.noninteraction;
// send
window.ga('send', 'event', event);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrder = function(track){
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
// orderId is required.
if (!orderId) return;
// require ecommerce
if (!this.ecommerce) {
window.ga('require', 'ecommerce', 'ecommerce.js');
this.ecommerce = true;
}
// add transaction
window.ga('ecommerce:addTransaction', {
affiliation: props.affiliation,
shipping: track.shipping(),
revenue: track.total(),
tax: track.tax(),
id: orderId
});
// add products
each(products, function(product){
var track = new Track({ properties: product });
window.ga('ecommerce:addItem', {
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
sku: track.sku(),
id: orderId
});
});
// send
window.ga('ecommerce:send');
};
/**
* Initialize (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*/
GA.prototype.initializeClassic = function () {
var opts = this.options;
var anonymize = opts.anonymizeIp;
var db = opts.doubleClick;
var domain = opts.domain;
var enhanced = opts.enhancedLinkAttribution;
var ignore = opts.ignoredReferrers;
var sample = opts.siteSpeedSampleRate;
window._gaq = window._gaq || [];
push('_setAccount', opts.trackingId);
push('_setAllowLinker', true);
if (anonymize) push('_gat._anonymizeIp');
if (domain) push('_setDomainName', domain);
if (sample) push('_setSiteSpeedSampleRate', sample);
if (enhanced) {
var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:';
var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
push('_require', 'inpage_linkid', pluginUrl);
}
if (ignore) {
if (!is.array(ignore)) ignore = [ignore];
each(ignore, function (domain) {
push('_addIgnoredRef', domain);
});
}
this.load();
};
/**
* Loaded? (classic)
*
* @return {Boolean}
*/
GA.prototype.loadedClassic = function () {
return !! (window._gaq && window._gaq.push !== Array.prototype.push);
};
/**
* Load the classic Google Analytics library.
*
* @param {Function} callback
*/
GA.prototype.loadClassic = function (callback) {
if (this.options.doubleClick) {
load('//stats.g.doubleclick.net/dc.js', callback);
} else {
load({
http: 'http://www.google-analytics.com/ga.js',
https: 'https://ssl.google-analytics.com/ga.js'
}, callback);
}
};
/**
* Page (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*
* @param {Page} page
*/
GA.prototype.pageClassic = function (page) {
var opts = page.options(this.name);
var category = page.category();
var props = page.properties();
var name = page.fullName();
var track;
push('_trackPageview', path(props, this.options));
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
*
* @param {Track} track
*/
GA.prototype.trackClassic = function (track, options) {
var opts = options || track.options(this.name);
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var category = this._category || props.category || 'All';
var label = props.label;
var value = formatValue(revenue || props.value);
var noninteraction = props.noninteraction || opts.noninteraction;
push('_trackEvent', category, event, label, value, noninteraction);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrderClassic = function(track){
var orderId = track.orderId();
var products = track.products() || [];
var props = track.properties();
// required
if (!orderId) return;
// add transaction
push('_addTrans'
, orderId
, props.affiliation
, track.total()
, track.tax()
, track.shipping()
, track.city()
, track.state()
, track.country());
// add items
each(products, function(product){
var track = new Track({ properties: product });
push('_addItem'
, orderId
, track.sku()
, track.name()
, track.category()
, track.price()
, track.quantity());
})
// send
push('_trackTrans');
};
/**
* Return the path based on `properties` and `options`.
*
* @param {Object} properties
* @param {Object} options
*/
function path (properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
}
/**
* Format the value property to Google's liking.
*
* @param {Number} value
* @return {Number}
*/
function formatValue (value) {
if (!value || value < 0) return 0;
return Math.round(value);
}
/**
* Map google's custom dimensions & metrics with `obj`.
*
* Example:
*
* metrics({ revenue: 1.9 }, { { metrics : { metric8: 'revenue' } });
* // => { metric8: 1.9 }
*
* metrics({ revenue: 1.9 }, {});
* // => {}
*
* @param {Object} obj
* @param {Object} data
* @return {Object|null}
* @api private
*/
function metrics(obj, data){
var dimensions = data.dimensions;
var metrics = data.metrics;
var names = keys(metrics).concat(keys(dimensions));
var ret = {};
for (var i = 0; i < names.length; ++i) {
var name = metrics[names[i]] || dimensions[names[i]];
var value = dot(obj, name);
if (null == value) continue;
ret[names[i]] = value;
}
return ret;
}
});
require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js", function(exports, require, module){
var push = require('global-queue')('dataLayer', { wrap: false });
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(GTM);
};
/**
* Expose `GTM`
*/
var GTM = exports.Integration = integration('Google Tag Manager')
.assumesPageview()
.readyOnLoad()
.global('dataLayer')
.global('google_tag_manager')
.option('containerId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
/**
* Initialize
*
* https://developers.google.com/tag-manager
*
* @param {Object} page
*/
GTM.prototype.initialize = function(){
this.load();
};
/**
* Loaded
*
* @return {Boolean}
*/
GTM.prototype.loaded = function(){
return !! (window.dataLayer && [].push != window.dataLayer.push);
};
/**
* Load.
*
* @param {Function} fn
*/
GTM.prototype.load = function(fn){
var id = this.options.containerId;
push({ 'gtm.start': +new Date, event: 'gtm.js' });
load('//www.googletagmanager.com/gtm.js?id=' + id + '&l=dataLayer', fn);
};
/**
* Page.
*
* @param {Page} page
* @api public
*/
GTM.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
var track;
// all
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Track.
*
* https://developers.google.com/tag-manager/devguide#events
*
* @param {Track} track
* @api public
*/
GTM.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
push(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/gosquared.js", function(exports, require, module){
var Identify = require('facade').Identify;
var Track = require('facade').Track;
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var onBody = require('on-body');
var each = require('each');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GoSquared);
user = analytics.user(); // store reference for later
};
/**
* Expose `GoSquared` integration.
*/
var GoSquared = exports.Integration = integration('GoSquared')
.assumesPageview()
.readyOnLoad()
.global('_gs')
.option('siteToken', '')
.option('anonymizeIP', false)
.option('cookieDomain', null)
.option('useCookies', true)
.option('trackHash', false)
.option('trackLocal', false)
.option('trackParams', true);
/**
* Initialize.
*
* https://www.gosquared.com/developer/tracker
* Options: https://www.gosquared.com/developer/tracker/configuration
*
* @param {Object} page
*/
GoSquared.prototype.initialize = function (page) {
var self = this;
var options = this.options;
push(options.siteToken);
each(options, function(name, value){
if ('siteToken' == name) return;
if (null == value) return;
push('set', name, value);
});
self.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
self.load();
};
/**
* Loaded? (checks if the tracker version is set)
*
* @return {Boolean}
*/
GoSquared.prototype.loaded = function () {
return !! (window._gs && window._gs.v);
};
/**
* Load the GoSquared library.
*
* @param {Function} callback
*/
GoSquared.prototype.load = function (callback) {
load('//d1l6p2sc9645hc.cloudfront.net/tracker.js', callback);
};
/**
* Page.
*
* https://www.gosquared.com/developer/tracker/pageviews
*
* @param {Page} page
*/
GoSquared.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
push('track', props.path, name || props.title)
};
/**
* Identify.
*
* https://www.gosquared.com/developer/tracker/tagging
*
* @param {Identify} identify
*/
GoSquared.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'userID' });
var username = identify.username();
var email = identify.email();
var id = identify.userId();
if (id) push('set', 'visitorID', id);
var name = email || username || id;
if (name) push('set', 'visitorName', name);
push('set', 'visitor', traits);
};
/**
* Track.
*
* https://www.gosquared.com/developer/tracker/events
*
* @param {Track} track
*/
GoSquared.prototype.track = function (track) {
push('event', track.event(), track.properties());
};
/**
* Checked out.
*
* @param {Track} track
* @api private
*/
GoSquared.prototype.completedOrder = function(track){
var products = track.products();
var items = [];
each(products, function(product){
var track = new Track({ properties: product });
items.push({
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
});
})
push('transaction', track.orderId(), {
revenue: track.total(),
track: true
}, items);
};
/**
* Push to `_gs.q`.
*
* @param {...} args
* @api private
*/
function push(){
var _gs = window._gs = window._gs || function(){
(_gs.q = _gs.q || []).push(arguments);
};
_gs.apply(null, arguments);
}
});
require.register("segmentio-analytics.js-integrations/lib/heap.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Heap);
};
/**
* Expose `Heap` integration.
*/
var Heap = exports.Integration = integration('Heap')
.assumesPageview()
.readyOnInitialize()
.global('heap')
.global('_heapid')
.option('apiKey', '');
/**
* Initialize.
*
* https://heapanalytics.com/docs#installWeb
*
* @param {Object} page
*/
Heap.prototype.initialize = function (page) {
window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);};
window.heap.load(this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Heap.prototype.loaded = function () {
return (window.heap && window.heap.appid);
};
/**
* Load the Heap library.
*
* @param {Function} callback
*/
Heap.prototype.load = function (callback) {
load('//d36lvucg9kzous.cloudfront.net', callback);
};
/**
* Identify.
*
* https://heapanalytics.com/docs#identify
*
* @param {Identify} identify
*/
Heap.prototype.identify = function (identify) {
var traits = identify.traits();
var username = identify.username();
var id = identify.userId();
var handle = username || id;
if (handle) traits.handle = handle;
delete traits.username;
window.heap.identify(traits);
};
/**
* Track.
*
* https://heapanalytics.com/docs#track
*
* @param {Track} track
*/
Heap.prototype.track = function (track) {
window.heap.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/hellobar.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Hellobar);
};
/**
* Expose `hellobar.com` integration.
*/
var Hellobar = exports.Integration = integration('Hello Bar')
.assumesPageview()
.readyOnInitialize()
.global('_hbq')
.option('apiKey', '');
/**
* Initialize.
*
* https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js
*
* @param {Object} page
*/
Hellobar.prototype.initialize = function(page) {
window._hbq = window._hbq || [];
this.load();
};
/**
* Load.
*
* @param {Function} callback
*/
Hellobar.prototype.load = function (callback) {
var url = '//s3.amazonaws.com/scripts.hellobar.com/' + this.options.apiKey + '.js';
load(url, callback);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Hellobar.prototype.loaded = function () {
return !! (window._hbq && window._hbq.push !== Array.prototype.push);
};
});
require.register("segmentio-analytics.js-integrations/lib/hittail.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(HitTail);
};
/**
* Expose `HitTail` integration.
*/
var HitTail = exports.Integration = integration('HitTail')
.assumesPageview()
.readyOnLoad()
.global('htk')
.option('siteId', '');
/**
* Initialize.
*
* @param {Object} page
*/
HitTail.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
HitTail.prototype.loaded = function () {
return is.fn(window.htk);
};
/**
* Load the HitTail library.
*
* @param {Function} callback
*/
HitTail.prototype.load = function (callback) {
var id = this.options.siteId;
load('//' + id + '.hittail.com/mlt.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/hubspot.js", function(exports, require, module){
var callback = require('callback');
var convert = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_hsq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(HubSpot);
};
/**
* Expose `HubSpot` integration.
*/
var HubSpot = exports.Integration = integration('HubSpot')
.assumesPageview()
.readyOnInitialize()
.global('_hsq')
.option('portalId', null);
/**
* Initialize.
*
* @param {Object} page
*/
HubSpot.prototype.initialize = function (page) {
window._hsq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
HubSpot.prototype.loaded = function () {
return !! (window._hsq && window._hsq.push !== Array.prototype.push);
};
/**
* Load the HubSpot library.
*
* @param {Function} fn
*/
HubSpot.prototype.load = function (fn) {
if (document.getElementById('hs-analytics')) return callback.async(fn);
var id = this.options.portalId;
var cache = Math.ceil(new Date() / 300000) * 300000;
var url = 'https://js.hs-analytics.net/analytics/' + cache + '/' + id + '.js';
var script = load(url, fn);
script.id = 'hs-analytics';
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
HubSpot.prototype.page = function (page) {
push('_trackPageview');
};
/**
* Identify.
*
* @param {Identify} identify
*/
HubSpot.prototype.identify = function (identify) {
if (!identify.email()) return;
var traits = identify.traits();
traits = convertDates(traits);
push('identify', traits);
};
/**
* Track.
*
* @param {Track} track
*/
HubSpot.prototype.track = function (track) {
var props = track.properties();
props = convertDates(props);
push('trackEvent', track.event(), props);
};
/**
* Convert all the dates in the HubSpot properties to millisecond times
*
* @param {Object} properties
*/
function convertDates (properties) {
return convert(properties, function (date) { return date.getTime(); });
}
});
require.register("segmentio-analytics.js-integrations/lib/improvely.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Improvely);
};
/**
* Expose `Improvely` integration.
*/
var Improvely = exports.Integration = integration('Improvely')
.assumesPageview()
.readyOnInitialize()
.global('_improvely')
.global('improvely')
.option('domain', '')
.option('projectId', null);
/**
* Initialize.
*
* http://www.improvely.com/docs/landing-page-code
*
* @param {Object} page
*/
Improvely.prototype.initialize = function (page) {
window._improvely = [];
window.improvely = {init: function (e, t) { window._improvely.push(["init", e, t]); }, goal: function (e) { window._improvely.push(["goal", e]); }, label: function (e) { window._improvely.push(["label", e]); } };
var domain = this.options.domain;
var id = this.options.projectId;
window.improvely.init(domain, id);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Improvely.prototype.loaded = function () {
return !! (window.improvely && window.improvely.identify);
};
/**
* Load the Improvely library.
*
* @param {Function} callback
*/
Improvely.prototype.load = function (callback) {
var domain = this.options.domain;
load('//' + domain + '.iljmp.com/improvely.js', callback);
};
/**
* Identify.
*
* http://www.improvely.com/docs/labeling-visitors
*
* @param {Identify} identify
*/
Improvely.prototype.identify = function (identify) {
var id = identify.userId();
if (id) window.improvely.label(id);
};
/**
* Track.
*
* http://www.improvely.com/docs/conversion-code
*
* @param {Track} track
*/
Improvely.prototype.track = function (track) {
var props = track.properties({ revenue: 'amount' });
props.type = track.event();
window.improvely.goal(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/inspectlet.js", function(exports, require, module){
var integration = require('integration');
var alias = require('alias');
var clone = require('clone');
var load = require('load-script');
var push = require('global-queue')('__insp');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Inspectlet);
};
/**
* Expose `Inspectlet` integration.
*/
var Inspectlet = exports.Integration = integration('Inspectlet')
.assumesPageview()
.readyOnLoad()
.global('__insp')
.global('__insp_')
.option('wid', '');
/**
* Initialize.
*
* https://www.inspectlet.com/dashboard/embedcode/1492461759/initial
*
* @param {Object} page
*/
Inspectlet.prototype.initialize = function (page) {
push('wid', this.options.wid);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Inspectlet.prototype.loaded = function () {
return !! window.__insp_;
};
/**
* Load the Inspectlet library.
*
* @param {Function} callback
*/
Inspectlet.prototype.load = function (callback) {
load('//www.inspectlet.com/inspectlet.js', callback);
};
/**
* Identify.
*
* http://www.inspectlet.com/docs#tagging
*
* @param {Identify} identify
*/
Inspectlet.prototype.identify = function (identify) {
var traits = identify.traits({ id: 'userid' });
push('tagSession', traits);
};
/**
* Track.
*
* http://www.inspectlet.com/docs/tags
*
* @param {Track} track
*/
Inspectlet.prototype.track = function (track) {
push('tagSession', track.event());
};
});
require.register("segmentio-analytics.js-integrations/lib/intercom.js", function(exports, require, module){
var alias = require('alias');
var convertDates = require('convert-dates');
var integration = require('integration');
var each = require('each');
var is = require('is');
var isEmail = require('is-email');
var load = require('load-script');
var defaults = require('defaults');
var empty = require('is-empty');
/* Group reference. */
var group;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Intercom);
group = analytics.group();
};
/**
* Expose `Intercom` integration.
*/
var Intercom = exports.Integration = integration('Intercom')
.assumesPageview()
.readyOnLoad()
.global('Intercom')
.option('activator', '#IntercomDefaultWidget')
.option('appId', '')
.option('inbox', false);
/**
* Initialize.
*
* http://docs.intercom.io/
* http://docs.intercom.io/#IntercomJS
*
* @param {Object} page
*/
Intercom.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Intercom.prototype.loaded = function () {
return is.fn(window.Intercom);
};
/**
* Load the Intercom library.
*
* @param {Function} callback
*/
Intercom.prototype.load = function (callback) {
load('https://static.intercomcdn.com/intercom.v1.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Intercom.prototype.page = function(page){
window.Intercom('update');
};
/**
* Identify.
*
* http://docs.intercom.io/#IntercomJS
*
* @param {Identify} identify
*/
Intercom.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'user_id' });
var activator = this.options.activator;
var opts = identify.options(this.name);
var companyCreated = identify.companyCreated();
var created = identify.created();
var email = identify.email();
var name = identify.name();
var id = identify.userId();
if (!id && !traits.email) return; // one is required
traits.app_id = this.options.appId;
// Make sure company traits are carried over (fixes #120).
if (!empty(group.traits())) {
traits.company = traits.company || {};
defaults(traits.company, group.traits());
}
// name
if (name) traits.name = name;
// handle dates
if (companyCreated) traits.company.created = companyCreated;
if (created) traits.created = created;
// convert dates
traits = convertDates(traits, formatDate);
traits = alias(traits, { created: 'created_at'});
// company
if (traits.company) {
traits.company = alias(traits.company, { created: 'created_at' });
}
// handle options
if (opts.increments) traits.increments = opts.increments;
if (opts.userHash) traits.user_hash = opts.userHash;
if (opts.user_hash) traits.user_hash = opts.user_hash;
// Intercom, will force the widget to appear
// if the selector is #IntercomDefaultWidget
// so no need to check inbox, just need to check
// that the selector isn't #IntercomDefaultWidget.
if ('#IntercomDefaultWidget' != activator) {
traits.widget = { activator: activator };
}
var method = this._id !== id ? 'boot': 'update';
this._id = id; // cache for next time
window.Intercom(method, traits);
};
/**
* Group.
*
* @param {Group} group
*/
Intercom.prototype.group = function (group) {
var props = group.properties();
var id = group.groupId();
if (id) props.id = id;
window.Intercom('update', { company: props });
};
/**
* Track.
*
* @param {Track} track
*/
Intercom.prototype.track = function(track){
window.Intercom('trackEvent', track.event(), track.properties());
};
/**
* Format a date to Intercom's liking.
*
* @param {Date} date
* @return {Number}
*/
function formatDate (date) {
return Math.floor(date / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/keen-io.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Keen);
};
/**
* Expose `Keen IO` integration.
*/
var Keen = exports.Integration = integration('Keen IO')
.readyOnInitialize()
.global('Keen')
.option('projectId', '')
.option('readKey', '')
.option('writeKey', '')
.option('trackNamedPages', true)
.option('trackAllPages', false)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://keen.io/docs/
*/
Keen.prototype.initialize = function () {
var options = this.options;
window.Keen = window.Keen||{configure:function(e){this._cf=e;},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i]);},setGlobalProperties:function(e){this._gp=e;},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e);}};
window.Keen.configure({
projectId: options.projectId,
writeKey: options.writeKey,
readKey: options.readKey
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Keen.prototype.loaded = function () {
return !! (window.Keen && window.Keen.Base64);
};
/**
* Load the Keen IO library.
*
* @param {Function} callback
*/
Keen.prototype.load = function (callback) {
load('//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Keen.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* TODO: migrate from old `userId` to simpler `id`
*
* @param {Identify} identify
*/
Keen.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
var user = {};
if (id) user.userId = id;
if (traits) user.traits = traits;
window.Keen.setGlobalProperties(function() {
return { user: user };
});
};
/**
* Track.
*
* @param {Track} track
*/
Keen.prototype.track = function (track) {
window.Keen.addEvent(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/kenshoo.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var is = require('is');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Kenshoo);
};
/**
* Expose `Kenshoo` integration.
*/
var Kenshoo = exports.Integration = integration('Kenshoo')
.readyOnLoad()
.global('k_trackevent')
.option('cid', '')
.option('subdomain', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* See https://gist.github.com/justinboyle/7875832
*
* @param {Object} page
*/
Kenshoo.prototype.initialize = function(page) {
this.load();
};
/**
* Loaded? (checks if the tracking function is set)
*
* @return {Boolean}
*/
Kenshoo.prototype.loaded = function() {
return is.fn(window.k_trackevent);
};
/**
* Load Kenshoo script.
*
* @param {Function} callback
*/
Kenshoo.prototype.load = function(callback) {
var url = '//' + this.options.subdomain + '.xg4ken.com/media/getpx.php?cid=' + this.options.cid;
load(url, callback);
};
/**
* Completed order.
*
* https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb
*
* @param {Track} track
* @api private
*/
Kenshoo.prototype.completedOrder = function(track) {
this._track(track, { val: track.total() });
};
/**
* Page.
*
* @param {Page} page
*/
Kenshoo.prototype.page = function(page) {
var category = page.category();
var name = page.name();
var fullName = page.fullName();
var isNamed = (name && this.options.trackNamedPages);
var isCategorized = (category && this.options.trackCategorizedPages);
var track;
if (name && ! this.options.trackNamedPages) {
return;
}
if (category && ! this.options.trackCategorizedPages) {
return;
}
if (isNamed && isCategorized) {
track = page.track(fullName);
} else if (isNamed) {
track = page.track(name);
} else if (isCategorized) {
track = page.track(category);
} else {
track = page.track();
}
this._track(track);
};
/**
* Track.
*
* https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb
*
* @param {Track} event
*/
Kenshoo.prototype.track = function(track) {
this._track(track);
};
/**
* Track a Kenshoo event.
*
* Private method for sending an event. We use it because `completedOrder`
* can't call track directly (would result in an infinite loop).
*
* @param {track} event
* @param {options} object
*/
Kenshoo.prototype._track = function(track, options) {
options = options || { val: track.revenue() };
var params = [
'id=' + this.options.cid,
'type=' + track.event(),
'val=' + (options.val || '0.0'),
'orderId=' + (track.orderId() || ''),
'promoCode=' + (track.coupon() || ''),
'valueCurrency=' + (track.currency() || ''),
// Live tracking fields. Ignored for now (until we get documentation).
'GCID=',
'kw=',
'product='
];
window.k_trackevent(params, this.options.subdomain);
};
});
require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js", function(exports, require, module){
var alias = require('alias');
var Batch = require('batch');
var callback = require('callback');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_kmq');
var Track = require('facade').Track;
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(KISSmetrics);
};
/**
* Expose `KISSmetrics` integration.
*/
var KISSmetrics = exports.Integration = integration('KISSmetrics')
.assumesPageview()
.readyOnInitialize()
.global('_kmq')
.global('KM')
.global('_kmil')
.option('apiKey', '')
.option('trackPages', true)
.option('prefixProperties', true);
/**
* Initialize.
*
* http://support.kissmetrics.com/apis/javascript
*
* @param {Object} page
*/
KISSmetrics.prototype.initialize = function (page) {
window._kmq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
KISSmetrics.prototype.loaded = function () {
return is.object(window.KM);
};
/**
* Load.
*
* @param {Function} callback
*/
KISSmetrics.prototype.load = function (callback) {
var key = this.options.apiKey;
var useless = '//i.kissmetrics.com/i.js';
var library = '//doug1izaerwt3.cloudfront.net/' + key + '.1.js';
new Batch()
.push(function (done) { load(useless, done); }) // :)
.push(function (done) { load(library, done); })
.end(callback);
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
KISSmetrics.prototype.page = function (page) {
var name = page.fullName();
var opts = this.options;
// named pages
if (name && opts.trackPages) {
var track = page.track(name);
this.track(track);
}
};
/**
* Identify.
*
* @param {Identify} identify
*/
KISSmetrics.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {Track} track
*/
KISSmetrics.prototype.track = function (track) {
var mapping = { revenue: 'Billing Amount' };
var event = track.event();
var properties = track.properties(mapping);
if (this.options.prefixProperties) properties = prefix(event, properties);
push('record', event, properties);
};
/**
* Alias.
*
* @param {Alias} to
*/
KISSmetrics.prototype.alias = function (alias) {
push('alias', alias.to(), alias.from());
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.completedOrder = function(track){
var products = track.products();
var event = track.event();
// transaction
push('record', event, prefix(event, track.properties()));
// items
window._kmq.push(function(){
var km = window.KM;
each(products, function(product, i){
var temp = new Track({ event: event, properties: product });
var item = prefix(event, product);
item._t = km.ts() + i;
item._d = 1;
km.set(item);
});
});
};
/**
* Prefix properties with the event name.
*
* @param {String} event
* @param {Object} properties
* @return {Object} prefixed
* @api private
*/
function prefix(event, properties){
var prefixed = {};
each(properties, function(key, val){
if (key === 'Billing Amount') {
prefixed[key] = val;
} else {
prefixed[event + ' - ' + key] = val;
}
});
return prefixed;
}
});
require.register("segmentio-analytics.js-integrations/lib/klaviyo.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_learnq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Klaviyo);
};
/**
* Expose `Klaviyo` integration.
*/
var Klaviyo = exports.Integration = integration('Klaviyo')
.assumesPageview()
.readyOnInitialize()
.global('_learnq')
.option('apiKey', '');
/**
* Initialize.
*
* https://www.klaviyo.com/docs/getting-started
*
* @param {Object} page
*/
Klaviyo.prototype.initialize = function (page) {
push('account', this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Klaviyo.prototype.loaded = function () {
return !! (window._learnq && window._learnq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Klaviyo.prototype.load = function (callback) {
load('//a.klaviyo.com/media/js/learnmarklet.js', callback);
};
/**
* Trait aliases.
*/
var aliases = {
id: '$id',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
phone: '$phone_number',
title: '$title'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Klaviyo.prototype.identify = function (identify) {
var traits = identify.traits(aliases);
if (!traits.$id && !traits.$email) return;
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
Klaviyo.prototype.group = function (group) {
var props = group.properties();
if (!props.name) return;
push('identify', { $organization: props.name });
};
/**
* Track.
*
* @param {Track} track
*/
Klaviyo.prototype.track = function (track) {
push('track', track.event(), track.properties({
revenue: '$value'
}));
};
});
require.register("segmentio-analytics.js-integrations/lib/leadlander.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LeadLander);
};
/**
* Expose `LeadLander` integration.
*/
var LeadLander = exports.Integration = integration('LeadLander')
.assumesPageview()
.readyOnLoad()
.global('llactid')
.global('trackalyzer')
.option('accountId', null);
/**
* Initialize.
*
* @param {Object} page
*/
LeadLander.prototype.initialize = function (page) {
window.llactid = this.options.accountId;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LeadLander.prototype.loaded = function () {
return !! window.trackalyzer;
};
/**
* Load.
*
* @param {Function} callback
*/
LeadLander.prototype.load = function (callback) {
load('http://t6.trackalyzer.com/trackalyze-nodoc.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/livechat.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var load = require('load-script');
var clone = require('clone');
var when = require('when');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LiveChat);
};
/**
* Expose `LiveChat` integration.
*/
var LiveChat = exports.Integration = integration('LiveChat')
.assumesPageview()
.readyOnLoad()
.global('__lc')
.global('__lc_inited')
.global('LC_API')
.global('LC_Invite')
.option('group', 0)
.option('license', '');
/**
* Initialize.
*
* http://www.livechatinc.com/api/javascript-api
*
* @param {Object} page
*/
LiveChat.prototype.initialize = function (page) {
window.__lc = clone(this.options);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LiveChat.prototype.loaded = function () {
return !!(window.LC_API && window.LC_Invite);
};
/**
* Load.
*
* @param {Function} callback
*/
LiveChat.prototype.load = function (callback) {
var self = this;
load('//cdn.livechatinc.com/tracking.js', function(err){
if (err) return callback(err);
when(function(){
return self.loaded();
}, callback);
});
};
/**
* Identify.
*
* @param {Identify} identify
*/
LiveChat.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'User ID' });
window.LC_API.set_custom_variables(convert(traits));
};
/**
* Convert a traits object into the format LiveChat requires.
*
* @param {Object} traits
* @return {Array}
*/
function convert (traits) {
var arr = [];
each(traits, function (key, value) {
arr.push({ name: key, value: value });
});
return arr;
}
});
require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js", function(exports, require, module){
var Identify = require('facade').Identify;
var integration = require('integration');
var load = require('load-script');
/**
* User ref
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LuckyOrange);
user = analytics.user();
};
/**
* Expose `LuckyOrange` integration.
*/
var LuckyOrange = exports.Integration = integration('Lucky Orange')
.assumesPageview()
.readyOnLoad()
.global('_loq')
.global('__wtw_watcher_added')
.global('__wtw_lucky_site_id')
.global('__wtw_lucky_is_segment_io')
.global('__wtw_custom_user_data')
.option('siteId', null);
/**
* Initialize.
*
* @param {Object} page
*/
LuckyOrange.prototype.initialize = function (page) {
window._loq || (window._loq = []);
window.__wtw_lucky_site_id = this.options.siteId;
this.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LuckyOrange.prototype.loaded = function () {
return !! window.__wtw_watcher_added;
};
/**
* Load.
*
* @param {Function} callback
*/
LuckyOrange.prototype.load = function (callback) {
var cache = Math.floor(new Date().getTime() / 60000);
load({
http: 'http://www.luckyorange.com/w.js?' + cache,
https: 'https://ssl.luckyorange.com/w.js?' + cache
}, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
LuckyOrange.prototype.identify = function (identify) {
var traits = window.__wtw_custom_user_data = identify.traits();
var email = identify.email();
var name = identify.name();
if (name) traits.name = name;
if (email) traits.email = email;
};
});
require.register("segmentio-analytics.js-integrations/lib/lytics.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Lytics);
};
/**
* Expose `Lytics` integration.
*/
var Lytics = exports.Integration = integration('Lytics')
.readyOnInitialize()
.global('jstag')
.option('cid', '')
.option('cookie', 'seerid')
.option('delay', 2000)
.option('sessionTimeout', 1800)
.option('url', '//c.lytics.io');
/**
* Options aliases.
*/
var aliases = {
sessionTimeout: 'sessecs'
};
/**
* Initialize.
*
* http://admin.lytics.io/doc#jstag
*
* @param {Object} page
*/
Lytics.prototype.initialize = function (page) {
var options = alias(this.options, aliases);
window.jstag = (function () {var t = {_q: [], _c: options, ts: (new Date()).getTime() }; t.send = function() {this._q.push([ 'ready', 'send', Array.prototype.slice.call(arguments) ]); return this; }; return t; })();
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Lytics.prototype.loaded = function () {
return !! (window.jstag && window.jstag.bind);
};
/**
* Load the Lytics library.
*
* @param {Function} callback
*/
Lytics.prototype.load = function (callback) {
load('//c.lytics.io/static/io.min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Lytics.prototype.page = function (page) {
window.jstag.send(page.properties());
};
/**
* Idenfity.
*
* @param {Identify} identify
*/
Lytics.prototype.identify = function (identify) {
var traits = identify.traits({ userId: '_uid' });
window.jstag.send(traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Lytics.prototype.track = function (track) {
var props = track.properties();
props._e = track.event();
window.jstag.send(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/mixpanel.js", function(exports, require, module){
var alias = require('alias');
var clone = require('clone');
var dates = require('convert-dates');
var integration = require('integration');
var iso = require('to-iso-string');
var load = require('load-script');
var indexof = require('indexof');
var del = require('obj-case').del;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Mixpanel);
};
/**
* Expose `Mixpanel` integration.
*/
var Mixpanel = exports.Integration = integration('Mixpanel')
.readyOnLoad()
.global('mixpanel')
.option('increments', [])
.option('cookieName', '')
.option('nameTag', true)
.option('pageview', false)
.option('people', false)
.option('token', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Options aliases.
*/
var optionsAliases = {
cookieName: 'cookie_name'
};
/**
* Initialize.
*
* https://mixpanel.com/help/reference/javascript#installing
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init
*/
Mixpanel.prototype.initialize = function () {
(function (c, a) {window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function (b, c, f) {function d(a, b) {var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function () {a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []);
this.options.increments = lowercase(this.options.increments);
var options = alias(this.options, optionsAliases);
window.mixpanel.init(options.token, options);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mixpanel.prototype.loaded = function () {
return !! (window.mixpanel && window.mixpanel.config);
};
/**
* Load.
*
* @param {Function} callback
*/
Mixpanel.prototype.load = function (callback) {
load('//cdn.mxpnl.com/libs/mixpanel-2.2.min.js', callback);
};
/**
* Page.
*
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Mixpanel.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Trait aliases.
*/
var traitAliases = {
created: '$created',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
lastSeen: '$last_seen',
name: '$name',
username: '$username',
phone: '$phone'
};
/**
* Identify.
*
* https://mixpanel.com/help/reference/javascript#super-properties
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript#storing-user-profiles
*
* @param {Identify} identify
*/
Mixpanel.prototype.identify = function (identify) {
var username = identify.username();
var email = identify.email();
var id = identify.userId();
// id
if (id) window.mixpanel.identify(id);
// name tag
var nametag = email || username || id;
if (nametag) window.mixpanel.name_tag(nametag);
// traits
var traits = identify.traits(traitAliases);
if (traits.$created) del(traits, 'createdAt');
window.mixpanel.register(traits);
if (this.options.people) window.mixpanel.people.set(traits);
};
/**
* Track.
*
* https://mixpanel.com/help/reference/javascript#sending-events
* https://mixpanel.com/help/reference/javascript#tracking-revenue
*
* @param {Track} track
*/
Mixpanel.prototype.track = function (track) {
var increments = this.options.increments;
var increment = track.event().toLowerCase();
var people = this.options.people;
var props = track.properties();
var revenue = track.revenue();
if (people && ~indexof(increments, increment)) {
window.mixpanel.people.increment(track.event());
window.mixpanel.people.set('Last ' + track.event(), new Date);
}
props = dates(props, iso);
window.mixpanel.track(track.event(), props);
if (revenue && people) {
window.mixpanel.people.track_charge(revenue);
}
};
/**
* Alias.
*
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias
*
* @param {Alias} alias
*/
Mixpanel.prototype.alias = function (alias) {
var mp = window.mixpanel;
var to = alias.to();
if (mp.get_distinct_id && mp.get_distinct_id() === to) return;
// HACK: internal mixpanel API to ensure we don't overwrite
if (mp.get_property && mp.get_property('$people_distinct_id') === to) return;
// although undocumented, mixpanel takes an optional original id
mp.alias(to, alias.from());
};
/**
* Lowercase the given `arr`.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
function lowercase(arr){
var ret = new Array(arr.length);
for (var i = 0; i < arr.length; ++i) {
ret[i] = String(arr[i]).toLowerCase();
}
return ret;
}
});
require.register("segmentio-analytics.js-integrations/lib/mojn.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
var is = require('is');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Mojn);
};
/**
* Expose `Mojn`
*/
var Mojn = exports.Integration = integration('Mojn')
.option('customerCode', '')
.global('_mojnTrack')
.readyOnInitialize();
/**
* Initialize.
*
* @param {Object} page
*/
Mojn.prototype.initialize = function(){
window._mojnTrack = window._mojnTrack || [];
window._mojnTrack.push({ cid: this.options.customerCode });
this.load();
};
/**
* Load the Mojn script.
*
* @param {Function} fn
*/
Mojn.prototype.load = function(fn) {
load('https://track.idtargeting.com/' + this.options.customerCode + '/track.js', fn);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mojn.prototype.loaded = function () {
return is.object(window._mojnTrack);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Mojn.prototype.identify = function(identify) {
var email = identify.email();
if (!email) return;
var img = new Image();
img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email;
img.width = 1;
img.height = 1;
return img;
};
/**
* Track.
*
* @param {Track} event
*/
Mojn.prototype.track = function(track) {
var properties = track.properties();
var revenue = properties.revenue;
var currency = properties.currency || '';
var conv = currency + revenue;
if (!revenue) return;
window._mojnTrack.push({ conv: conv });
return conv;
};
});
require.register("segmentio-analytics.js-integrations/lib/mouseflow.js", function(exports, require, module){
var push = require('global-queue')('_mfq');
var integration = require('integration');
var load = require('load-script');
var each = require('each');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Mouseflow);
};
/**
* Expose `Mouseflow`
*/
var Mouseflow = exports.Integration = integration('Mouseflow')
.assumesPageview()
.readyOnLoad()
.global('mouseflow')
.global('_mfq')
.option('apiKey', '')
.option('mouseflowHtmlDelay', 0);
/**
* Iniitalize
*
* @param {Object} page
*/
Mouseflow.prototype.initialize = function(page){
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mouseflow.prototype.loaded = function(){
return !! (window._mfq && [].push != window._mfq.push);
};
/**
* Load mouseflow.
*
* @param {Function} fn
*/
Mouseflow.prototype.load = function(fn){
var apiKey = this.options.apiKey;
window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay;
load('//cdn.mouseflow.com/projects/' + apiKey + '.js', fn);
};
/**
* Page.
*
* //mouseflow.zendesk.com/entries/22528817-Single-page-websites
*
* @param {Page} page
*/
Mouseflow.prototype.page = function(page){
if (!window.mouseflow) return;
if ('function' != typeof mouseflow.newPageView) return;
mouseflow.newPageView();
};
/**
* Identify.
*
* //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Identify} identify
*/
Mouseflow.prototype.identify = function(identify){
set(identify.traits());
};
/**
* Track.
*
* //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Track} track
*/
Mouseflow.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
set(props);
};
/**
* Push the given `hash`.
*
* @param {Object} hash
*/
function set(hash){
each(hash, function(k, v){
push('setVariable', k, v);
});
}
});
require.register("segmentio-analytics.js-integrations/lib/mousestats.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(MouseStats);
};
/**
* Expose `MouseStats` integration.
*/
var MouseStats = exports.Integration = integration('MouseStats')
.assumesPageview()
.readyOnLoad()
.global('msaa')
.option('accountNumber', '');
/**
* Initialize.
*
* http://www.mousestats.com/docs/pages/allpages
*
* @param {Object} page
*/
MouseStats.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
MouseStats.prototype.loaded = function () {
return is.fn(window.msaa);
};
/**
* Load.
*
* @param {Function} callback
*/
MouseStats.prototype.load = function (callback) {
var number = this.options.accountNumber;
var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number;
var cache = Math.floor(new Date().getTime() / 60000);
var partial = '.mousestats.com/js/' + path + '.js?' + cache;
var http = 'http://www2' + partial;
var https = 'https://ssl' + partial;
load({ http: http, https: https }, callback);
};
/**
* Identify.
*
* http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks
*
* @param {Identify} identify
*/
MouseStats.prototype.identify = function (identify) {
each(identify.traits(), function (key, value) {
window.MouseStatsVisitorPlaybacks.customVariable(key, value);
});
};
});
require.register("segmentio-analytics.js-integrations/lib/navilytics.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('__nls');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Navilytics);
};
/**
* Expose `Navilytics` integration.
*/
var Navilytics = exports.Integration = integration('Navilytics')
.assumesPageview()
.readyOnLoad()
.global('__nls')
.option('memberId', '')
.option('projectId', '');
/**
* Initialize.
*
* https://www.navilytics.com/member/code_settings
*
* @param {Object} page
*/
Navilytics.prototype.initialize = function(page){
window.__nls = window.__nls || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Navilytics.prototype.loaded = function(){
return !! (window.__nls && [].push != window.__nls.push);
};
/**
* Load the Navilytics library.
*
* @param {Function} callback
*/
Navilytics.prototype.load = function(callback){
var mid = this.options.memberId;
var pid = this.options.projectId;
var url = '//www.navilytics.com/nls.js?mid=' + mid + '&pid=' + pid;
load(url, callback);
};
/**
* Track.
*
* https://www.navilytics.com/docs#tags
*
* @param {Track} track
*/
Navilytics.prototype.track = function(track){
push('tagRecording', track.event());
};
});
require.register("segmentio-analytics.js-integrations/lib/olark.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var https = require('use-https');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Olark);
};
/**
* Expose `Olark` integration.
*/
var Olark = exports.Integration = integration('Olark')
.assumesPageview()
.readyOnInitialize()
.global('olark')
.option('identify', true)
.option('page', true)
.option('siteId', '')
.option('track', false);
/**
* Initialize.
*
* http://www.olark.com/documentation
*
* @param {Object} page
*/
Olark.prototype.initialize = function (page) {
window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});
window.olark.identify(this.options.siteId);
// keep track of the widget's open state
var self = this;
box('onExpand', function () { self._open = true; });
box('onShrink', function () { self._open = false; });
};
/**
* Page.
*
* @param {Page} page
*/
Olark.prototype.page = function (page) {
if (!this.options.page || !this._open) return;
var props = page.properties();
var name = page.fullName();
if (!name && !props.url) return;
var msg = name ? name.toLowerCase() + ' page' : props.url;
chat('sendNotificationToOperator', {
body: 'looking at ' + msg // lowercase since olark does
});
};
/**
* Identify.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
*/
Olark.prototype.identify = function (identify) {
if (!this.options.identify) return;
var username = identify.username();
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
var phone = identify.phone();
var name = identify.name()
|| identify.firstName();
visitor('updateCustomFields', traits);
if (email) visitor('updateEmailAddress', { emailAddress: email });
if (phone) visitor('updatePhoneNumber', { phoneNumber: phone });
// figure out best name
if (name) visitor('updateFullName', { fullName: name });
// figure out best nickname
var nickname = name || email || username || id;
if (name && email) nickname += ' (' + email + ')';
if (nickname) chat('updateVisitorNickname', { snippet: nickname });
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Olark.prototype.track = function (track) {
if (!this.options.track || !this._open) return;
chat('sendNotificationToOperator', {
body: 'visitor triggered "' + track.event() + '"' // lowercase since olark does
});
};
/**
* Helper method for Olark box API calls.
*
* @param {String} action
* @param {Object} value
*/
function box (action, value) {
window.olark('api.box.' + action, value);
}
/**
* Helper method for Olark visitor API calls.
*
* @param {String} action
* @param {Object} value
*/
function visitor (action, value) {
window.olark('api.visitor.' + action, value);
}
/**
* Helper method for Olark chat API calls.
*
* @param {String} action
* @param {Object} value
*/
function chat (action, value) {
window.olark('api.chat.' + action, value);
}
});
require.register("segmentio-analytics.js-integrations/lib/optimizely.js", function(exports, require, module){
var bind = require('bind');
var callback = require('callback');
var each = require('each');
var integration = require('integration');
var push = require('global-queue')('optimizely');
var tick = require('next-tick');
/**
* Analytics reference.
*/
var analytics;
/**
* Expose plugin.
*/
module.exports = exports = function (ajs) {
ajs.addIntegration(Optimizely);
analytics = ajs; // store for later
};
/**
* Expose `Optimizely` integration.
*/
var Optimizely = exports.Integration = integration('Optimizely')
.readyOnInitialize()
.option('variations', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://www.optimizely.com/docs/api#function-calls
*/
Optimizely.prototype.initialize = function () {
if (this.options.variations) tick(this.replay);
};
/**
* Track.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Track} track
*/
Optimizely.prototype.track = function (track) {
var props = track.properties();
if (props.revenue) props.revenue *= 100;
push('trackEvent', track.event(), props);
};
/**
* Page.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Page} page
*/
Optimizely.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Replay experiment data as traits to other enabled providers.
*
* https://www.optimizely.com/docs/api#data-object
*/
Optimizely.prototype.replay = function () {
if (!window.optimizely) return; // in case the snippet isnt on the page
var data = window.optimizely.data;
if (!data) return;
var experiments = data.experiments;
var map = data.state.variationNamesMap;
var traits = {};
each(map, function (experimentId, variation) {
var experiment = experiments[experimentId].name;
traits['Experiment: ' + experiment] = variation;
});
analytics.identify(traits);
};
});
require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(PerfectAudience);
};
/**
* Expose `PerfectAudience` integration.
*/
var PerfectAudience = exports.Integration = integration('Perfect Audience')
.assumesPageview()
.readyOnLoad()
.global('_pa')
.option('siteId', '');
/**
* Initialize.
*
* https://www.perfectaudience.com/docs#javascript_api_autoopen
*
* @param {Object} page
*/
PerfectAudience.prototype.initialize = function (page) {
window._pa = window._pa || {};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
PerfectAudience.prototype.loaded = function () {
return !! (window._pa && window._pa.track);
};
/**
* Load.
*
* @param {Function} callback
*/
PerfectAudience.prototype.load = function (callback) {
var id = this.options.siteId;
load('//tag.perfectaudience.com/serve/' + id + '.js', callback);
};
/**
* Track.
*
* @param {Track} event
*/
PerfectAudience.prototype.track = function (track) {
window._pa.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/pingdom.js", function(exports, require, module){
var date = require('load-date');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_prum');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Pingdom);
};
/**
* Expose `Pingdom` integration.
*/
var Pingdom = exports.Integration = integration('Pingdom')
.assumesPageview()
.readyOnLoad()
.global('_prum')
.option('id', '');
/**
* Initialize.
*
* @param {Object} page
*/
Pingdom.prototype.initialize = function (page) {
window._prum = window._prum || [];
push('id', this.options.id);
push('mark', 'firstbyte', date.getTime());
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Pingdom.prototype.loaded = function () {
return !! (window._prum && window._prum.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Pingdom.prototype.load = function (callback) {
load('//rum-static.pingdom.net/prum.min.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/piwik.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_paq');
/**
* Expose plugin
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Piwik);
};
/**
* Expose `Piwik` integration.
*/
var Piwik = exports.Integration = integration('Piwik')
.global('_paq')
.option('url', null)
.option('siteId', '')
.assumesPageview()
.readyOnInitialize();
/**
* Initialize.
*
* http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking
*/
Piwik.prototype.initialize = function () {
window._paq = window._paq || [];
push('setSiteId', this.options.siteId);
push('setTrackerUrl', this.options.url + '/piwik.php');
push('enableLinkTracking');
this.load();
};
/**
* Load the Piwik Analytics library.
*/
Piwik.prototype.load = function (callback) {
load(this.options.url + "/piwik.js", callback);
};
/**
* Check if Piwik is loaded
*/
Piwik.prototype.loaded = function () {
return !! (window._paq && window._paq.push != [].push);
};
/**
* Page
*
* @param {Page} page
*/
Piwik.prototype.page = function (page) {
push('trackPageView');
};
});
require.register("segmentio-analytics.js-integrations/lib/preact.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_lnq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Preact);
};
/**
* Expose `Preact` integration.
*/
var Preact = exports.Integration = integration('Preact')
.assumesPageview()
.readyOnInitialize()
.global('_lnq')
.option('projectCode', '');
/**
* Initialize.
*
* http://www.preact.io/api/javascript
*
* @param {Object} page
*/
Preact.prototype.initialize = function (page) {
window._lnq = window._lnq || [];
push('_setCode', this.options.projectCode);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Preact.prototype.loaded = function () {
return !! (window._lnq && window._lnq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Preact.prototype.load = function (callback) {
load('//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Preact.prototype.identify = function (identify) {
if (!identify.userId()) return;
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
push('_setPersonData', {
name: identify.name(),
email: identify.email(),
uid: identify.userId(),
properties: traits
});
};
/**
* Group.
*
* @param {String} id
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Preact.prototype.group = function (group) {
if (!group.groupId()) return;
push('_setAccount', group.traits());
};
/**
* Track.
*
* @param {Track} track
*/
Preact.prototype.track = function (track) {
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var special = { name: event };
if (revenue) {
special.revenue = revenue * 100;
delete props.revenue;
}
if (props.note) {
special.note = props.note;
delete props.note;
}
push('_logEvent', special, props);
};
/**
* Convert a `date` to a format Preact supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate (date) {
return Math.floor(date / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/qualaroo.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_kiq');
var Facade = require('facade');
var Identify = Facade.Identify;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Qualaroo);
};
/**
* Expose `Qualaroo` integration.
*/
var Qualaroo = exports.Integration = integration('Qualaroo')
.assumesPageview()
.readyOnInitialize()
.global('_kiq')
.option('customerId', '')
.option('siteToken', '')
.option('track', false);
/**
* Initialize.
*
* @param {Object} page
*/
Qualaroo.prototype.initialize = function (page) {
window._kiq = window._kiq || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Qualaroo.prototype.loaded = function () {
return !! (window._kiq && window._kiq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Qualaroo.prototype.load = function (callback) {
var token = this.options.siteToken;
var id = this.options.customerId;
load('//s3.amazonaws.com/ki.js/' + id + '/' + token + '.js', callback);
};
/**
* Identify.
*
* http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers
* http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties
*
* @param {Identify} identify
*/
Qualaroo.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
if (email) id = email;
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Qualaroo.prototype.track = function (track) {
if (!this.options.track) return;
var event = track.event();
var traits = {};
traits['Triggered: ' + event] = true;
this.identify(new Identify({ traits: traits }));
};
});
require.register("segmentio-analytics.js-integrations/lib/quantcast.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_qevents', { wrap: false });
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Quantcast);
user = analytics.user(); // store for later
};
/**
* Expose `Quantcast` integration.
*/
var Quantcast = exports.Integration = integration('Quantcast')
.assumesPageview()
.readyOnInitialize()
.global('_qevents')
.global('__qc')
.option('pCode', null)
.option('advertise', false);
/**
* Initialize.
*
* https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {Page} page
*/
Quantcast.prototype.initialize = function (page) {
window._qevents = window._qevents || [];
var opts = this.options;
var settings = { qacct: opts.pCode };
if (user.id()) settings.uid = user.id();
if (page) {
settings.labels = this.labels('page', page.category(), page.name());
}
push(settings);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Quantcast.prototype.loaded = function () {
return !! window.__qc;
};
/**
* Load.
*
* @param {Function} callback
*/
Quantcast.prototype.load = function (callback) {
load({
http: 'http://edge.quantserve.com/quant.js',
https: 'https://secure.quantserve.com/quant.js'
}, callback);
};
/**
* Page.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Page} page
*/
Quantcast.prototype.page = function (page) {
var category = page.category();
var name = page.name();
var settings = {
event: 'refresh',
labels: this.labels('page', category, name),
qacct: this.options.pCode,
};
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Identify.
*
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {String} id (optional)
*/
Quantcast.prototype.identify = function (identify) {
// edit the initial quantcast settings
var id = identify.userId();
if (id) window._qevents[0].uid = id;
};
/**
* Track.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Track} track
*/
Quantcast.prototype.track = function (track) {
var name = track.event();
var revenue = track.revenue();
var settings = {
event: 'click',
labels: this.labels('event', name),
qacct: this.options.pCode
};
if (null != revenue) settings.revenue = (revenue+''); // convert to string
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
Quantcast.prototype.completedOrder = function(track){
var name = track.event();
var revenue = track.total();
var labels = this.labels('event', name);
var category = track.category();
if (this.options.advertise && category) {
labels += ',' + this.labels('pcat', category);
}
var settings = {
event: 'refresh', // the example Quantcast sent has completed order send refresh not click
labels: labels,
revenue: (revenue+''), // convert to string
orderid: track.orderId(),
qacct: this.options.pCode
};
push(settings);
};
/**
* Generate quantcast labels.
*
* Example:
*
* options.advertise = false;
* labels('event', 'my event');
* // => "event.my event"
*
* options.advertise = true;
* labels('event', 'my event');
* // => "_fp.event.my event"
*
* @param {String} type
* @param {String} ...
* @return {String}
* @api private
*/
Quantcast.prototype.labels = function(type){
var args = [].slice.call(arguments, 1);
var advertise = this.options.advertise;
var ret = [];
if (advertise && 'page' == type) type = 'event';
if (advertise) type = '_fp.' + type;
for (var i = 0; i < args.length; ++i) {
if (null == args[i]) continue;
var value = String(args[i]);
ret.push(value.replace(/,/g, ';'));
}
ret = advertise ? ret.join(' ') : ret.join('.');
return [type, ret].join('.');
};
});
require.register("segmentio-analytics.js-integrations/lib/rollbar.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var is = require('is');
var extend = require('extend');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics) {
analytics.addIntegration(RollbarIntegration);
};
/**
* Expose `Rollbar` integration.
*/
var RollbarIntegration = exports.Integration = integration('Rollbar')
.readyOnInitialize()
.global('Rollbar')
.option('identify', true)
.option('accessToken', '')
.option('environment', 'unknown')
.option('captureUncaught', true);
/**
* Initialize.
*
* @param {Object} page
*/
RollbarIntegration.prototype.initialize = function(page) {
var _rollbarConfig = this.config = {
accessToken: this.options.accessToken,
captureUncaught: this.options.captureUncaught,
payload: {
environment: this.options.environment
}
};
!function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)}(window,document);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
RollbarIntegration.prototype.loaded = function() {
return is.object(window.Rollbar) && null == window.Rollbar.shimId;
};
/**
* Load.
*
* @param {Function} callback
*/
RollbarIntegration.prototype.load = function(callback) {
window.Rollbar.loadFull(window, document, true, this.config, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
RollbarIntegration.prototype.identify = function(identify) {
// do stuff with `id` or `traits`
if (!this.options.identify) return;
// Don't allow identify without a user id
var uid = identify.userId();
if (uid === null || uid === undefined) return;
var rollbar = window.Rollbar;
var person = {id: uid};
extend(person, identify.traits());
rollbar.configure({payload: {person: person}});
};
});
require.register("segmentio-analytics.js-integrations/lib/saasquatch.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(SaaSquatch);
};
/**
* Expose `SaaSquatch` integration.
*/
var SaaSquatch = exports.Integration = integration('SaaSquatch')
.readyOnInitialize()
.option('tenantAlias', '')
.global('_sqh');
/**
* Initialize
*
* @param {Page} page
*/
SaaSquatch.prototype.initialize = function(page){};
/**
* Loaded?
*
* @return {Boolean}
*/
SaaSquatch.prototype.loaded = function(){
return window._sqh && window._sqh.push != [].push;
};
/**
* Load the SaaSquatch library.
*
* @param {Function} fn
*/
SaaSquatch.prototype.load = function(fn){
load('//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js', fn);
};
/**
* Identify.
*
* @param {Facade} identify
*/
SaaSquatch.prototype.identify = function(identify){
var sqh = window._sqh = window._sqh || [];
var accountId = identify.proxy('traits.accountId');
var image = identify.proxy('traits.referralImage');
var opts = identify.options(this.name);
var id = identify.userId();
var email = identify.email();
if (!(id || email)) return;
if (this.called) return;
var init = {
tenant_alias: this.options.tenantAlias,
first_name: identify.firstName(),
last_name: identify.lastName(),
user_image: identify.avatar(),
email: email,
user_id: id,
};
if (accountId) init.account_id = accountId;
if (opts.checksum) init.checksum = opts.checksum;
if (image) init.fb_share_image = image;
sqh.push(['init', init]);
this.called = true;
this.load();
};
});
require.register("segmentio-analytics.js-integrations/lib/sentry.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Sentry);
};
/**
* Expose `Sentry` integration.
*/
var Sentry = exports.Integration = integration('Sentry')
.readyOnLoad()
.global('Raven')
.option('config', '');
/**
* Initialize.
*
* http://raven-js.readthedocs.org/en/latest/config/index.html
*/
Sentry.prototype.initialize = function () {
var config = this.options.config;
this.load(function () {
// for now, raven basically requires `install` to be called
// https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113
window.Raven.config(config).install();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Sentry.prototype.loaded = function () {
return is.object(window.Raven);
};
/**
* Load.
*
* @param {Function} callback
*/
Sentry.prototype.load = function (callback) {
load('//cdn.ravenjs.com/1.1.10/native/raven.min.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Sentry.prototype.identify = function (identify) {
window.Raven.setUser(identify.traits());
};
});
require.register("segmentio-analytics.js-integrations/lib/snapengage.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(SnapEngage);
};
/**
* Expose `SnapEngage` integration.
*/
var SnapEngage = exports.Integration = integration('SnapEngage')
.assumesPageview()
.readyOnLoad()
.global('SnapABug')
.option('apiKey', '');
/**
* Initialize.
*
* http://help.snapengage.com/installation-guide-getting-started-in-a-snap/
*
* @param {Object} page
*/
SnapEngage.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
SnapEngage.prototype.loaded = function () {
return is.object(window.SnapABug);
};
/**
* Load.
*
* @param {Function} callback
*/
SnapEngage.prototype.load = function (callback) {
var key = this.options.apiKey;
var url = '//commondatastorage.googleapis.com/code.snapengage.com/js/' + key + '.js';
load(url, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
SnapEngage.prototype.identify = function (identify) {
var email = identify.email();
if (!email) return;
window.SnapABug.setUserEmail(email);
};
});
require.register("segmentio-analytics.js-integrations/lib/spinnakr.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Spinnakr);
};
/**
* Expose `Spinnakr` integration.
*/
var Spinnakr = exports.Integration = integration('Spinnakr')
.assumesPageview()
.readyOnLoad()
.global('_spinnakr_site_id')
.global('_spinnakr')
.option('siteId', '');
/**
* Initialize.
*
* @param {Object} page
*/
Spinnakr.prototype.initialize = function (page) {
window._spinnakr_site_id = this.options.siteId;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Spinnakr.prototype.loaded = function () {
return !! window._spinnakr;
};
/**
* Load.
*
* @param {Function} callback
*/
Spinnakr.prototype.load = function (callback) {
load('//d3ojzyhbolvoi5.cloudfront.net/js/so.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/tapstream.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var slug = require('slug');
var push = require('global-queue')('_tsq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Tapstream);
};
/**
* Expose `Tapstream` integration.
*/
var Tapstream = exports.Integration = integration('Tapstream')
.assumesPageview()
.readyOnInitialize()
.global('_tsq')
.option('accountName', '')
.option('trackAllPages', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* @param {Object} page
*/
Tapstream.prototype.initialize = function (page) {
window._tsq = window._tsq || [];
push('setAccountName', this.options.accountName);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Tapstream.prototype.loaded = function () {
return !! (window._tsq && window._tsq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Tapstream.prototype.load = function (callback) {
load('//cdn.tapstream.com/static/js/tapstream.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Tapstream.prototype.page = function (page) {
var category = page.category();
var opts = this.options;
var name = page.fullName();
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Track.
*
* @param {Track} track
*/
Tapstream.prototype.track = function (track) {
var props = track.properties();
push('fireHit', slug(track.event()), [props.url]); // needs events as slugs
};
});
require.register("segmentio-analytics.js-integrations/lib/trakio.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var clone = require('clone');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Trakio);
};
/**
* Expose `Trakio` integration.
*/
var Trakio = exports.Integration = integration('trak.io')
.assumesPageview()
.readyOnInitialize()
.global('trak')
.option('token', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Options aliases.
*/
var optionsAliases = {
initialPageview: 'auto_track_page_view'
};
/**
* Initialize.
*
* https://docs.trak.io
*
* @param {Object} page
*/
Trakio.prototype.initialize = function (page) {
var self = this;
var options = this.options;
window.trak = window.trak || [];
window.trak.io = window.trak.io || {};
window.trak.io.load = function(e) {self.load(); var r = function(e) {return function() {window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); };
window.trak.io.load(options.token, alias(options, optionsAliases));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Trakio.prototype.loaded = function () {
return !! (window.trak && window.trak.loaded);
};
/**
* Load the trak.io library.
*
* @param {Function} callback
*/
Trakio.prototype.load = function (callback) {
load('//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Trakio.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
window.trak.io.page_view(props.path, name || props.title);
// named pages
if (name && this.options.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && this.options.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Trait aliases.
*
* http://docs.trak.io/properties.html#special
*/
var traitAliases = {
avatar: 'avatar_url',
firstName: 'first_name',
lastName: 'last_name'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Trakio.prototype.identify = function (identify) {
var traits = identify.traits(traitAliases);
var id = identify.userId();
if (id) {
window.trak.io.identify(id, traits);
} else {
window.trak.io.identify(traits);
}
};
/**
* Group.
*
* @param {String} id (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*
* TODO: add group
* TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special
*/
/**
* Track.
*
* @param {Track} track
*/
Trakio.prototype.track = function (track) {
window.trak.io.track(track.event(), track.properties());
};
/**
* Alias.
*
* @param {Alias} alias
*/
Trakio.prototype.alias = function (alias) {
if (!window.trak.io.distinct_id) return;
var from = alias.from();
var to = alias.to();
if (to === window.trak.io.distinct_id()) return;
if (from) {
window.trak.io.alias(from, to);
} else {
window.trak.io.alias(to);
}
};
});
require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js", function(exports, require, module){
var pixel = require('load-pixel')('//analytics.twitter.com/i/adsct');
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(TwitterAds);
};
/**
* Expose `load`
*/
exports.load = pixel;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `TwitterAds`
*/
var TwitterAds = exports.Integration = integration('Twitter Ads')
.readyOnInitialize()
.option('events', {});
/**
* Track.
*
* @param {Track} track
*/
TwitterAds.prototype.track = function(track){
var events = this.options.events;
var event = track.event();
if (!has.call(events, event)) return;
return exports.load({
txn_id: events[event],
p_id: 'Twitter'
});
};
});
require.register("segmentio-analytics.js-integrations/lib/usercycle.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_uc');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Usercycle);
};
/**
* Expose `Usercycle` integration.
*/
var Usercycle = exports.Integration = integration('USERcycle')
.assumesPageview()
.readyOnInitialize()
.global('_uc')
.option('key', '');
/**
* Initialize.
*
* http://docs.usercycle.com/javascript_api
*
* @param {Object} page
*/
Usercycle.prototype.initialize = function (page) {
push('_key', this.options.key);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Usercycle.prototype.loaded = function () {
return !! (window._uc && window._uc.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Usercycle.prototype.load = function (callback) {
load('//api.usercycle.com/javascripts/track.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Usercycle.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
if (id) push('uid', id);
// there's a special `came_back` event used for retention and traits
push('action', 'came_back', traits);
};
/**
* Track.
*
* @param {Track} track
*/
Usercycle.prototype.track = function (track) {
push('action', track.event(), track.properties({
revenue: 'revenue_amount'
}));
};
});
require.register("segmentio-analytics.js-integrations/lib/userfox.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_ufq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Userfox);
};
/**
* Expose `Userfox` integration.
*/
var Userfox = exports.Integration = integration('userfox')
.assumesPageview()
.readyOnInitialize()
.global('_ufq')
.option('clientId', '');
/**
* Initialize.
*
* https://www.userfox.com/docs/
*
* @param {Object} page
*/
Userfox.prototype.initialize = function (page) {
window._ufq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Userfox.prototype.loaded = function () {
return !! (window._ufq && window._ufq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Userfox.prototype.load = function (callback) {
load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js', callback);
};
/**
* Identify.
*
* https://www.userfox.com/docs/#custom-data
*
* @param {Identify} identify
*/
Userfox.prototype.identify = function (identify) {
var traits = identify.traits({ created: 'signup_date' });
var email = identify.email();
if (!email) return;
// initialize the library with the email now that we have it
push('init', {
clientId: this.options.clientId,
email: email
});
traits = convertDates(traits, formatDate);
push('track', traits);
};
/**
* Convert a `date` to a format userfox supports.
*
* @param {Date} date
* @return {String}
*/
function formatDate (date) {
return Math.round(date.getTime() / 1000).toString();
}
});
require.register("segmentio-analytics.js-integrations/lib/uservoice.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var clone = require('clone');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('UserVoice');
var unix = require('to-unix-timestamp');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(UserVoice);
};
/**
* Expose `UserVoice` integration.
*/
var UserVoice = exports.Integration = integration('UserVoice')
.assumesPageview()
.readyOnInitialize()
.global('UserVoice')
.global('showClassicWidget')
.option('apiKey', '')
.option('classic', false)
.option('forumId', null)
.option('showWidget', true)
.option('mode', 'contact')
.option('accentColor', '#448dd6')
.option('smartvote', true)
.option('trigger', null)
.option('triggerPosition', 'bottom-right')
.option('triggerColor', '#ffffff')
.option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)')
// BACKWARDS COMPATIBILITY: classic options
.option('classicMode', 'full')
.option('primaryColor', '#cc6d00')
.option('linkColor', '#007dbf')
.option('defaultMode', 'support')
.option('tabLabel', 'Feedback & Support')
.option('tabColor', '#cc6d00')
.option('tabPosition', 'middle-right')
.option('tabInverted', false);
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
UserVoice.on('construct', function (integration) {
if (!integration.options.classic) return;
integration.group = undefined;
integration.identify = integration.identifyClassic;
integration.initialize = integration.initializeClassic;
});
/**
* Initialize.
*
* @param {Object} page
*/
UserVoice.prototype.initialize = function (page) {
var options = this.options;
var opts = formatOptions(options);
push('set', opts);
push('autoprompt', {});
if (options.showWidget) {
options.trigger
? push('addTrigger', options.trigger, opts)
: push('addTrigger', opts);
}
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
UserVoice.prototype.loaded = function () {
return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
UserVoice.prototype.load = function (callback) {
var key = this.options.apiKey;
load('//widget.uservoice.com/' + key + '.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
UserVoice.prototype.identify = function (identify) {
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
UserVoice.prototype.group = function (group) {
var traits = group.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', { account: traits });
};
/**
* Initialize (classic).
*
* @param {Object} options
* @param {Function} ready
*/
UserVoice.prototype.initializeClassic = function () {
var options = this.options;
window.showClassicWidget = showClassicWidget; // part of public api
if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options));
this.load();
};
/**
* Identify (classic).
*
* @param {Identify} identify
*/
UserVoice.prototype.identifyClassic = function (identify) {
push('setCustomFields', identify.traits());
};
/**
* Format the options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatOptions (options) {
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position'
});
}
/**
* Format the classic options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatClassicOptions (options) {
return alias(options, {
forumId: 'forum_id',
classicMode: 'mode',
primaryColor: 'primary_color',
tabPosition: 'tab_position',
tabColor: 'tab_color',
linkColor: 'link_color',
defaultMode: 'default_mode',
tabLabel: 'tab_label',
tabInverted: 'tab_inverted'
});
}
/**
* Show the classic version of the UserVoice widget. This method is usually part
* of UserVoice classic's public API.
*
* @param {String} type ('showTab' or 'showLightbox')
* @param {Object} options (optional)
*/
function showClassicWidget (type, options) {
type = type || 'showLightbox';
push(type, 'classic_widget', options);
}
});
require.register("segmentio-analytics.js-integrations/lib/vero.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_veroq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Vero);
};
/**
* Expose `Vero` integration.
*/
var Vero = exports.Integration = integration('Vero')
.readyOnInitialize()
.global('_veroq')
.option('apiKey', '');
/**
* Initialize.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md
*
* @param {Object} page
*/
Vero.prototype.initialize = function (pgae) {
push('init', { api_key: this.options.apiKey });
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Vero.prototype.loaded = function () {
return !! (window._veroq && window._veroq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Vero.prototype.load = function (callback) {
load('//d3qxef4rp70elm.cloudfront.net/m.js', callback);
};
/**
* Page.
*
* https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews
*
* @param {Page} page
*/
Vero.prototype.page = function(page){
push('trackPageview');
};
/**
* Identify.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification
*
* @param {Identify} identify
*/
Vero.prototype.identify = function (identify) {
var traits = identify.traits();
var email = identify.email();
var id = identify.userId();
if (!id || !email) return; // both required
push('user', traits);
};
/**
* Track.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events
*
* @param {Track} track
*/
Vero.prototype.track = function (track) {
push('track', track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", function(exports, require, module){
var callback = require('callback');
var each = require('each');
var integration = require('integration');
var tick = require('next-tick');
/**
* Analytics reference.
*/
var analytics;
/**
* Expose plugin.
*/
module.exports = exports = function (ajs) {
ajs.addIntegration(VWO);
analytics = ajs;
};
/**
* Expose `VWO` integration.
*/
var VWO = exports.Integration = integration('Visual Website Optimizer')
.readyOnInitialize()
.option('replay', true);
/**
* Initialize.
*
* http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php
*/
VWO.prototype.initialize = function () {
if (this.options.replay) this.replay();
};
/**
* Replay the experiments the user has seen as traits to all other integrations.
* Wait for the next tick to replay so that the `analytics` object and all of
* the integrations are fully initialized.
*/
VWO.prototype.replay = function () {
tick(function () {
experiments(function (err, traits) {
if (traits) analytics.identify(traits);
});
});
};
/**
* Get dictionary of experiment keys and variations.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {Function} callback
* @return {Object}
*/
function experiments (callback) {
enqueue(function () {
var data = {};
var ids = window._vwo_exp_ids;
if (!ids) return callback();
each(ids, function (id) {
var name = variation(id);
if (name) data['Experiment: ' + id] = name;
});
callback(null, data);
});
}
/**
* Add a `fn` to the VWO queue, creating one if it doesn't exist.
*
* @param {Function} fn
*/
function enqueue (fn) {
window._vis_opt_queue = window._vis_opt_queue || [];
window._vis_opt_queue.push(fn);
}
/**
* Get the chosen variation's name from an experiment `id`.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {String} id
* @return {String}
*/
function variation (id) {
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
}
});
require.register("segmentio-analytics.js-integrations/lib/webengage.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(WebEngage);
};
/**
* Expose `WebEngage` integration
*/
var WebEngage = exports.Integration = integration('WebEngage')
.assumesPageview()
.readyOnLoad()
.global('_weq')
.global('webengage')
.option('widgetVersion', '4.0')
.option('licenseCode', '');
/**
* Initialize.
*
* @param {Object} page
*/
WebEngage.prototype.initialize = function(page){
var _weq = window._weq = window._weq || {};
_weq['webengage.licenseCode'] = this.options.licenseCode;
_weq['webengage.widgetVersion'] = this.options.widgetVersion;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
WebEngage.prototype.loaded = function(){
return !! window.webengage;
};
/**
* Load
*
* @param {Function} fn
*/
WebEngage.prototype.load = function(fn){
var path = '/js/widget/webengage-min-v-4.0.js';
load({
https: 'https://ssl.widgets.webengage.com' + path,
http: 'http://cdn.widgets.webengage.com' + path
}, fn);
};
});
require.register("segmentio-analytics.js-integrations/lib/woopra.js", function(exports, require, module){
var each = require('each');
var extend = require('extend');
var integration = require('integration');
var isEmail = require('is-email');
var load = require('load-script');
var type = require('type');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Woopra);
};
/**
* Expose `Woopra` integration.
*/
var Woopra = exports.Integration = integration('Woopra')
.readyOnLoad()
.global('woopra')
.option('domain', '');
/**
* Initialize.
*
* http://www.woopra.com/docs/setup/javascript-tracking/
*
* @param {Object} page
*/
Woopra.prototype.initialize = function (page) {
(function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra');
window.woopra.config({ domain: this.options.domain });
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Woopra.prototype.loaded = function () {
return !! (window.woopra && window.woopra.loaded);
};
/**
* Load.
*
* @param {Function} callback
*/
Woopra.prototype.load = function (callback) {
load('//static.woopra.com/js/w.js', callback);
};
/**
* Page.
*
* @param {String} category (optional)
*/
Woopra.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
if (name) props.title = name;
window.woopra.track('pv', props);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Woopra.prototype.identify = function (identify) {
window.woopra.identify(identify.traits()).push(); // `push` sends it off async
};
/**
* Track.
*
* @param {Track} track
*/
Woopra.prototype.track = function (track) {
window.woopra.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Yandex);
};
/**
* Expose `Yandex` integration.
*/
var Yandex = exports.Integration = integration('Yandex Metrica')
.assumesPageview()
.readyOnInitialize()
.global('yandex_metrika_callbacks')
.global('Ya')
.option('counterId', null);
/**
* Initialize.
*
* http://api.yandex.com/metrika/
* https://metrica.yandex.com/22522351?step=2#tab=code
*
* @param {Object} page
*/
Yandex.prototype.initialize = function (page) {
var id = this.options.counterId;
push(function () {
window['yaCounter' + id] = new window.Ya.Metrika({ id: id });
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Yandex.prototype.loaded = function () {
return !! (window.Ya && window.Ya.Metrika);
};
/**
* Load.
*
* @param {Function} callback
*/
Yandex.prototype.load = function (callback) {
load('//mc.yandex.ru/metrika/watch.js', callback);
};
/**
* Push a new callback on the global Yandex queue.
*
* @param {Function} callback
*/
function push (callback) {
window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || [];
window.yandex_metrika_callbacks.push(callback);
}
});
require.register("segmentio-canonical/index.js", function(exports, require, module){
module.exports = function canonical () {
var tags = document.getElementsByTagName('link');
for (var i = 0, tag; tag = tags[i]; i++) {
if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href');
}
};
});
require.register("segmentio-extend/index.js", function(exports, require, module){
module.exports = function extend (object) {
// Takes an unlimited number of extenders.
var args = Array.prototype.slice.call(arguments, 1);
// For each extender, copy their properties on our object.
for (var i = 0, source; source = args[i]; i++) {
if (!source) continue;
for (var property in source) {
object[property] = source[property];
}
}
return object;
};
});
require.register("camshaft-require-component/index.js", function(exports, require, module){
/**
* Require a module with a fallback
*/
module.exports = function(parent) {
function require(name, fallback) {
try {
return parent(name);
}
catch (e) {
try {
return parent(fallback || name+"-component");
}
catch(e2) {
throw e;
}
}
};
// Merge the old properties
for (var key in parent) {
require[key] = parent[key];
}
return require;
};
});
require.register("segmentio-facade/lib/index.js", function(exports, require, module){
var Facade = require('./facade');
/**
* Expose `Facade` facade.
*/
module.exports = Facade;
/**
* Expose specific-method facades.
*/
Facade.Alias = require('./alias');
Facade.Group = require('./group');
Facade.Identify = require('./identify');
Facade.Track = require('./track');
Facade.Page = require('./page');
Facade.Screen = require('./screen');
});
require.register("segmentio-facade/lib/alias.js", function(exports, require, module){
/**
* Module dependencies.
*/
var Facade = require('./facade');
var component = require('require-component')(require);
var inherit = component('inherit');
/**
* Expose `Alias` facade.
*/
module.exports = Alias;
/**
* Initialize a new `Alias` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @property {String} from
* @property {String} to
* @property {Object} options
*/
function Alias (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Alias, Facade);
/**
* Return type of facade.
*
* @return {String}
*/
Alias.prototype.type =
Alias.prototype.action = function () {
return 'alias';
};
/**
* Get `previousId`.
*
* @return {Mixed}
* @api public
*/
Alias.prototype.from =
Alias.prototype.previousId = function(){
return this.field('previousId')
|| this.field('from');
};
/**
* Get `userId`.
*
* @return {String}
* @api public
*/
Alias.prototype.to =
Alias.prototype.userId = function(){
return this.field('userId')
|| this.field('to');
};
});
require.register("segmentio-facade/lib/facade.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var isEnabled = component('./is-enabled');
var objCase = component('obj-case');
var traverse = component('isodate-traverse');
/**
* Expose `Facade`.
*/
module.exports = Facade;
/**
* Initialize a new `Facade` with an `obj` of arguments.
*
* @param {Object} obj
*/
function Facade (obj) {
if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date();
else obj.timestamp = new Date(obj.timestamp);
this.obj = obj;
}
/**
* Return a proxy function for a `field` that will attempt to first use methods,
* and fallback to accessing the underlying object directly. You can specify
* deeply nested fields too like:
*
* this.proxy('options.Librato');
*
* @param {String} field
*/
Facade.prototype.proxy = function (field) {
var fields = field.split('.');
field = fields.shift();
// Call a function at the beginning to take advantage of facaded fields
var obj = this[field] || this.field(field);
if (!obj) return obj;
if (typeof obj === 'function') obj = obj.call(this) || {};
if (fields.length === 0) return transform(obj);
obj = objCase(obj, fields.join('.'));
return transform(obj);
};
/**
* Directly access a specific `field` from the underlying object, returning a
* clone so outsiders don't mess with stuff.
*
* @param {String} field
* @return {Mixed}
*/
Facade.prototype.field = function (field) {
var obj = this.obj[field];
return transform(obj);
};
/**
* Utility method to always proxy a particular `field`. You can specify deeply
* nested fields too like:
*
* Facade.proxy('options.Librato');
*
* @param {String} field
* @return {Function}
*/
Facade.proxy = function (field) {
return function () {
return this.proxy(field);
};
};
/**
* Utility method to directly access a `field`.
*
* @param {String} field
* @return {Function}
*/
Facade.field = function (field) {
return function () {
return this.field(field);
};
};
/**
* Get the basic json object of this facade.
*
* @return {Object}
*/
Facade.prototype.json = function () {
return clone(this.obj);
};
/**
* Get the options of a call (formerly called "context"). If you pass an
* integration name, it will get the options for that specific integration, or
* undefined if the integration is not enabled.
*
* @param {String} integration (optional)
* @return {Object or Null}
*/
Facade.prototype.context =
Facade.prototype.options = function (integration) {
var options = clone(this.obj.options || this.obj.context) || {};
if (!integration) return clone(options);
if (!this.enabled(integration)) return;
var integrations = this.integrations();
var value = integrations[integration] || objCase(integrations, integration);
if ('boolean' == typeof value) value = {};
return value || {};
};
/**
* Check whether an integration is enabled.
*
* @param {String} integration
* @return {Boolean}
*/
Facade.prototype.enabled = function (integration) {
var allEnabled = this.proxy('options.providers.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all');
if (typeof allEnabled !== 'boolean') allEnabled = true;
var enabled = allEnabled && isEnabled(integration);
var options = this.integrations();
// If the integration is explicitly enabled or disabled, use that
// First, check options.providers for backwards compatibility
if (options.providers && options.providers.hasOwnProperty(integration)) {
enabled = options.providers[integration];
}
// Next, check for the integration's existence in 'options' to enable it.
// If the settings are a boolean, use that, otherwise it should be enabled.
if (options.hasOwnProperty(integration)) {
var settings = options[integration];
if (typeof settings === 'boolean') {
enabled = settings;
} else {
enabled = true;
}
}
return enabled ? true : false;
};
/**
* Get all `integration` options.
*
* @param {String} integration
* @return {Object}
* @api private
*/
Facade.prototype.integrations = function(){
return this.obj.integrations
|| this.proxy('options.providers')
|| this.options();
};
/**
* Check whether the user is active.
*
* @return {Boolean}
*/
Facade.prototype.active = function () {
var active = this.proxy('options.active');
if (active === null || active === undefined) active = true;
return active;
};
/**
* Get `sessionId / anonymousId`.
*
* @return {Mixed}
* @api public
*/
Facade.prototype.sessionId =
Facade.prototype.anonymousId = function(){
return this.field('anonymousId')
|| this.field('sessionId');
};
/**
* Add a convenient way to get the library name and version
*/
Facade.prototype.library = function(){
var library = this.proxy('options.library');
if (!library) return { name: 'unknown', version: null };
if (typeof library === 'string') return { name: library, version: null };
return library;
};
/**
* Setup some basic proxies.
*/
Facade.prototype.userId = Facade.field('userId');
Facade.prototype.channel = Facade.field('channel');
Facade.prototype.timestamp = Facade.field('timestamp');
Facade.prototype.userAgent = Facade.proxy('options.userAgent');
Facade.prototype.ip = Facade.proxy('options.ip');
/**
* Return the cloned and traversed object
*
* @param {Mixed} obj
* @return {Mixed}
*/
function transform(obj){
var cloned = clone(obj);
traverse(cloned);
return cloned;
}
});
require.register("segmentio-facade/lib/group.js", function(exports, require, module){
var Facade = require('./facade');
var component = require('require-component')(require);
var inherit = component('inherit');
var newDate = component('new-date');
/**
* Expose `Group` facade.
*/
module.exports = Group;
/**
* Initialize a new `Group` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} groupId
* @param {Object} properties
* @param {Object} options
*/
function Group (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Group, Facade);
/**
* Get the facade's action.
*/
Group.prototype.type =
Group.prototype.action = function () {
return 'group';
};
/**
* Setup some basic proxies.
*/
Group.prototype.groupId = Facade.field('groupId');
/**
* Get created or createdAt.
*
* @return {Date}
*/
Group.prototype.created = function(){
var created = this.proxy('traits.createdAt')
|| this.proxy('traits.created')
|| this.proxy('properties.createdAt')
|| this.proxy('properties.created');
if (created) return newDate(created);
};
/**
* Get the group's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Group.prototype.traits = function (aliases) {
var ret = this.properties();
var id = this.groupId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get traits or properties.
*
* TODO: remove me
*
* @return {Object}
*/
Group.prototype.properties = function(){
return this.field('traits')
|| this.field('properties')
|| {};
};
});
require.register("segmentio-facade/lib/page.js", function(exports, require, module){
var component = require('require-component')(require);
var Facade = component('./facade');
var inherit = component('inherit');
var Track = require('./track');
/**
* Expose `Page` facade
*/
module.exports = Page;
/**
* Initialize new `Page` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Page(dictionary){
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Page, Facade);
/**
* Get the facade's action.
*
* @return {String}
*/
Page.prototype.type =
Page.prototype.action = function(){
return 'page';
};
/**
* Proxies
*/
Page.prototype.category = Facade.field('category');
Page.prototype.name = Facade.field('name');
/**
* Get the page properties mixing `category` and `name`.
*
* @return {Object}
*/
Page.prototype.properties = function(){
var props = this.field('properties') || {};
var category = this.category();
var name = this.name();
if (category) props.category = category;
if (name) props.name = name;
return props;
};
/**
* Get the page fullName.
*
* @return {String}
*/
Page.prototype.fullName = function(){
var category = this.category();
var name = this.name();
return name && category
? category + ' ' + name
: name;
};
/**
* Get event with `name`.
*
* @return {String}
*/
Page.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Page'
: 'Loaded a Page';
};
/**
* Convert this Page to a Track facade with `name`.
*
* @param {String} name
* @return {Track}
*/
Page.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
properties: props
});
};
});
require.register("segmentio-facade/lib/identify.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var Facade = component('./facade');
var inherit = component('inherit');
var isEmail = component('is-email');
var newDate = component('new-date');
var trim = component('trim');
/**
* Expose `Idenfity` facade.
*/
module.exports = Identify;
/**
* Initialize a new `Identify` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} sessionId
* @param {Object} traits
* @param {Object} options
*/
function Identify (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Identify, Facade);
/**
* Get the facade's action.
*/
Identify.prototype.type =
Identify.prototype.action = function () {
return 'identify';
};
/**
* Get the user's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Identify.prototype.traits = function (aliases) {
var ret = this.field('traits') || {};
var id = this.userId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the user's email, falling back to their user ID if it's a valid email.
*
* @return {String}
*/
Identify.prototype.email = function () {
var email = this.proxy('traits.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the user's created date, optionally looking for `createdAt` since lots of
* people do that instead.
*
* @return {Date or Undefined}
*/
Identify.prototype.created = function () {
var created = this.proxy('traits.created') || this.proxy('traits.createdAt');
if (created) return newDate(created);
};
/**
* Get the company created date.
*
* @return {Date or undefined}
*/
Identify.prototype.companyCreated = function(){
var created = this.proxy('traits.company.created')
|| this.proxy('traits.company.createdAt');
if (created) return newDate(created);
};
/**
* Get the user's name, optionally combining a first and last name if that's all
* that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.name = function () {
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name);
var firstName = this.firstName();
var lastName = this.lastName();
if (firstName && lastName) return trim(firstName + ' ' + lastName);
};
/**
* Get the user's first name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.firstName = function () {
var firstName = this.proxy('traits.firstName');
if (typeof firstName === 'string') return trim(firstName);
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name).split(' ')[0];
};
/**
* Get the user's last name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.lastName = function () {
var lastName = this.proxy('traits.lastName');
if (typeof lastName === 'string') return trim(lastName);
var name = this.proxy('traits.name');
if (typeof name !== 'string') return;
var space = trim(name).indexOf(' ');
if (space === -1) return;
return trim(name.substr(space + 1));
};
/**
* Get the user's unique id.
*
* @return {String or undefined}
*/
Identify.prototype.uid = function(){
return this.userId()
|| this.username()
|| this.email();
};
/**
* Get description.
*
* @return {String}
*/
Identify.prototype.description = function(){
return this.proxy('traits.description')
|| this.proxy('traits.background');
};
/**
* Setup sme basic "special" trait proxies.
*/
Identify.prototype.username = Facade.proxy('traits.username');
Identify.prototype.website = Facade.proxy('traits.website');
Identify.prototype.phone = Facade.proxy('traits.phone');
Identify.prototype.address = Facade.proxy('traits.address');
Identify.prototype.avatar = Facade.proxy('traits.avatar');
});
require.register("segmentio-facade/lib/is-enabled.js", function(exports, require, module){
/**
* A few integrations are disabled by default. They must be explicitly
* enabled by setting options[Provider] = true.
*/
var disabled = {
Salesforce: true,
Marketo: true
};
/**
* Check whether an integration should be enabled by default.
*
* @param {String} integration
* @return {Boolean}
*/
module.exports = function (integration) {
return ! disabled[integration];
};
});
require.register("segmentio-facade/lib/track.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var Facade = component('./facade');
var Identify = component('./identify');
var inherit = component('inherit');
var isEmail = component('is-email');
/**
* Expose `Track` facade.
*/
module.exports = Track;
/**
* Initialize a new `Track` facade with a `dictionary` of arguments.
*
* @param {object} dictionary
* @property {String} event
* @property {String} userId
* @property {String} sessionId
* @property {Object} properties
* @property {Object} options
*/
function Track (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Track, Facade);
/**
* Return the facade's action.
*
* @return {String}
*/
Track.prototype.type =
Track.prototype.action = function () {
return 'track';
};
/**
* Setup some basic proxies.
*/
Track.prototype.event = Facade.field('event');
Track.prototype.value = Facade.proxy('properties.value');
/**
* Misc
*/
Track.prototype.category = Facade.proxy('properties.category');
Track.prototype.country = Facade.proxy('properties.country');
Track.prototype.state = Facade.proxy('properties.state');
Track.prototype.city = Facade.proxy('properties.city');
Track.prototype.zip = Facade.proxy('properties.zip');
/**
* Ecommerce
*/
Track.prototype.id = Facade.proxy('properties.id');
Track.prototype.sku = Facade.proxy('properties.sku');
Track.prototype.tax = Facade.proxy('properties.tax');
Track.prototype.name = Facade.proxy('properties.name');
Track.prototype.price = Facade.proxy('properties.price');
Track.prototype.total = Facade.proxy('properties.total');
Track.prototype.coupon = Facade.proxy('properties.coupon');
Track.prototype.shipping = Facade.proxy('properties.shipping');
/**
* Order id.
*
* @return {String}
* @api public
*/
Track.prototype.orderId = function(){
return this.proxy('properties.id')
|| this.proxy('properties.orderId');
};
/**
* Get subtotal.
*
* @return {Number}
*/
Track.prototype.subtotal = function(){
var subtotal = this.obj.properties.subtotal;
var total = this.total();
var n;
if (subtotal) return subtotal;
if (!total) return 0;
if (n = this.tax()) total -= n;
if (n = this.shipping()) total -= n;
return total;
};
/**
* Get products.
*
* @return {Array}
*/
Track.prototype.products = function(){
var props = this.obj.properties || {};
return props.products || [];
};
/**
* Get quantity.
*
* @return {Number}
*/
Track.prototype.quantity = function(){
var props = this.obj.properties || {};
return props.quantity || 1;
};
/**
* Get currency.
*
* @return {String}
*/
Track.prototype.currency = function(){
var props = this.obj.properties || {};
return props.currency || 'USD';
};
/**
* BACKWARDS COMPATIBILITY: should probably re-examine where these come from.
*/
Track.prototype.referrer = Facade.proxy('properties.referrer');
Track.prototype.query = Facade.proxy('options.query');
/**
* Get the call's properties.
*
* @param {Object} aliases
* @return {Object}
*/
Track.prototype.properties = function (aliases) {
var ret = this.field('properties') || {};
aliases = aliases || {};
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('properties.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the call's "super properties" which are just traits that have been
* passed in as if from an identify call.
*
* @return {Object}
*/
Track.prototype.traits = function () {
return this.proxy('options.traits') || {};
};
/**
* Get the call's username.
*
* @return {String or Undefined}
*/
Track.prototype.username = function () {
return this.proxy('traits.username') ||
this.proxy('properties.username') ||
this.userId() ||
this.sessionId();
};
/**
* Get the call's email, using an the user ID if it's a valid email.
*
* @return {String or Undefined}
*/
Track.prototype.email = function () {
var email = this.proxy('traits.email');
email = email || this.proxy('properties.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the call's revenue, parsing it from a string with an optional leading
* dollar sign.
*
* For products/services that don't have shipping and are not directly taxed,
* they only care about tracking `revenue`. These are things like
* SaaS companies, who sell monthly subscriptions. The subscriptions aren't
* taxed directly, and since it's a digital product, it has no shipping.
*
* The only case where there's a difference between `revenue` and `total`
* (in the context of analytics) is on ecommerce platforms, where they want
* the `revenue` function to actually return the `total` (which includes
* tax and shipping, total = subtotal + tax + shipping). This is probably
* because on their backend they assume tax and shipping has been applied to
* the value, and so can get the revenue on their own.
*
* @return {Number}
*/
Track.prototype.revenue = function () {
var revenue = this.proxy('properties.revenue');
var event = this.event();
// it's always revenue, unless it's called during an order completion.
if (!revenue && event && event.match(/completed ?order/i)) {
revenue = this.proxy('properties.total');
}
return currency(revenue);
};
/**
* Get cents.
*
* @return {Number}
*/
Track.prototype.cents = function(){
var revenue = this.revenue();
return 'number' != typeof revenue
? this.value() || 0
: revenue * 100;
};
/**
* A utility to turn the pieces of a track call into an identify. Used for
* integrations with super properties or rate limits.
*
* TODO: remove me.
*
* @return {Facade}
*/
Track.prototype.identify = function () {
var json = this.json();
json.traits = this.traits();
return new Identify(json);
};
/**
* Get float from currency value.
*
* @param {Mixed} val
* @return {Number}
*/
function currency(val) {
if (!val) return;
if (typeof val === 'number') return val;
if (typeof val !== 'string') return;
val = val.replace(/\$/g, '');
val = parseFloat(val);
if (!isNaN(val)) return val;
}
});
require.register("segmentio-facade/lib/screen.js", function(exports, require, module){
var component = require('require-component')(require);
var inherit = component('inherit');
var Page = component('./page');
var Track = require('./track');
/**
* Expose `Screen` facade
*/
module.exports = Screen;
/**
* Initialize new `Screen` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Screen(dictionary){
Page.call(this, dictionary);
}
/**
* Inherit from `Page`
*/
inherit(Screen, Page);
/**
* Get the facade's action.
*
* @return {String}
* @api public
*/
Screen.prototype.type =
Screen.prototype.action = function(){
return 'screen';
};
/**
* Get event with `name`.
*
* @param {String} name
* @return {String}
* @api public
*/
Screen.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Screen'
: 'Loaded a Screen';
};
/**
* Convert this Screen.
*
* @param {String} name
* @return {Track}
* @api public
*/
Screen.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
properties: props
});
};
});
require.register("segmentio-is-email/index.js", function(exports, require, module){
/**
* Expose `isEmail`.
*/
module.exports = isEmail;
/**
* Email address matcher.
*/
var matcher = /.+\@.+\..+/;
/**
* Loosely validate an email address.
*
* @param {String} string
* @return {Boolean}
*/
function isEmail (string) {
return matcher.test(string);
}
});
require.register("segmentio-is-meta/index.js", function(exports, require, module){
module.exports = function isMeta (e) {
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true;
// Logic that handles checks for the middle mouse button, based
// on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466).
var which = e.which, button = e.button;
if (!which && button !== undefined) {
return (!button & 1) && (!button & 2) && (button & 4);
} else if (which === 2) {
return true;
}
return false;
};
});
require.register("segmentio-isodate/index.js", function(exports, require, module){
/**
* Matcher, slightly modified from:
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*/
var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;
/**
* Convert an ISO date string to a date. Fallback to native `Date.parse`.
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*
* @param {String} iso
* @return {Date}
*/
exports.parse = function (iso) {
var numericKeys = [1, 5, 6, 7, 8, 11, 12];
var arr = matcher.exec(iso);
var offset = 0;
// fallback to native parsing
if (!arr) return new Date(iso);
// remove undefined values
for (var i = 0, val; val = numericKeys[i]; i++) {
arr[val] = parseInt(arr[val], 10) || 0;
}
// allow undefined days and months
arr[2] = parseInt(arr[2], 10) || 1;
arr[3] = parseInt(arr[3], 10) || 1;
// month is 0-11
arr[2]--;
// allow abitrary sub-second precision
if (arr[8]) arr[8] = (arr[8] + '00').substring(0, 3);
// apply timezone if one exists
if (arr[4] == ' ') {
offset = new Date().getTimezoneOffset();
} else if (arr[9] !== 'Z' && arr[10]) {
offset = arr[11] * 60 + arr[12];
if ('+' == arr[10]) offset = 0 - offset;
}
var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]);
return new Date(millis);
};
/**
* Checks whether a `string` is an ISO date string. `strict` mode requires that
* the date string at least have a year, month and date.
*
* @param {String} string
* @param {Boolean} strict
* @return {Boolean}
*/
exports.is = function (string, strict) {
if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false;
return matcher.test(string);
};
});
require.register("segmentio-isodate-traverse/index.js", function(exports, require, module){
var is = require('is');
var isodate = require('isodate');
var each;
try {
each = require('each');
} catch (err) {
each = require('each-component');
}
/**
* Expose `traverse`.
*/
module.exports = traverse;
/**
* Traverse an object or array, and return a clone with all ISO strings parsed
* into Date objects.
*
* @param {Object} obj
* @return {Object}
*/
function traverse (input, strict) {
if (strict === undefined) strict = true;
if (is.object(input)) {
return object(input, strict);
} else if (is.array(input)) {
return array(input, strict);
}
}
/**
* Object traverser.
*
* @param {Object} obj
* @param {Boolean} strict
* @return {Object}
*/
function object (obj, strict) {
each(obj, function (key, val) {
if (isodate.is(val, strict)) {
obj[key] = isodate.parse(val);
} else if (is.object(val) || is.array(val)) {
traverse(val, strict);
}
});
return obj;
}
/**
* Array traverser.
*
* @param {Array} arr
* @param {Boolean} strict
* @return {Array}
*/
function array (arr, strict) {
each(arr, function (val, x) {
if (is.object(val)) {
traverse(val, strict);
} else if (isodate.is(val, strict)) {
arr[x] = isodate.parse(val);
}
});
return arr;
}
});
require.register("component-json-fallback/index.js", function(exports, require, module){
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
(function () {
'use strict';
var JSON = module.exports = {};
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
});
require.register("segmentio-json/index.js", function(exports, require, module){
var json = window.JSON || {};
var stringify = json.stringify;
var parse = json.parse;
module.exports = parse && stringify
? JSON
: require('json-fallback');
});
require.register("segmentio-new-date/lib/index.js", function(exports, require, module){
var is = require('is');
var isodate = require('isodate');
var milliseconds = require('./milliseconds');
var seconds = require('./seconds');
/**
* Returns a new Javascript Date object, allowing a variety of extra input types
* over the native Date constructor.
*
* @param {Date|String|Number} val
*/
module.exports = function newDate (val) {
if (is.date(val)) return val;
if (is.number(val)) return new Date(toMs(val));
// date strings
if (isodate.is(val)) return isodate.parse(val);
if (milliseconds.is(val)) return milliseconds.parse(val);
if (seconds.is(val)) return seconds.parse(val);
// fallback to Date.parse
return new Date(val);
};
/**
* If the number passed val is seconds from the epoch, turn it into milliseconds.
* Milliseconds would be greater than 31557600000 (December 31, 1970).
*
* @param {Number} num
*/
function toMs (num) {
if (num < 31557600000) return num * 1000;
return num;
}
});
require.register("segmentio-new-date/lib/milliseconds.js", function(exports, require, module){
/**
* Matcher.
*/
var matcher = /\d{13}/;
/**
* Check whether a string is a millisecond date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a millisecond string to a date.
*
* @param {String} millis
* @return {Date}
*/
exports.parse = function (millis) {
millis = parseInt(millis, 10);
return new Date(millis);
};
});
require.register("segmentio-new-date/lib/seconds.js", function(exports, require, module){
/**
* Matcher.
*/
var matcher = /\d{10}/;
/**
* Check whether a string is a second date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a second string to a date.
*
* @param {String} seconds
* @return {Date}
*/
exports.parse = function (seconds) {
var millis = parseInt(seconds, 10) * 1000;
return new Date(millis);
};
});
require.register("segmentio-store.js/store.js", function(exports, require, module){
;(function(win){
var store = {},
doc = win.document,
localStorageName = 'localStorage',
namespace = '__storejs__',
storage
store.disabled = false
store.set = function(key, value) {}
store.get = function(key) {}
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key)
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (typeof val == 'undefined') { val = defaultVal || {} }
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.serialize = function(value) {
return JSON.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return JSON.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key) { return store.deserialize(storage.getItem(key)) }
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
for (var i=0; i<storage.length; ++i) {
var key = storage.key(i)
ret[key] = store.get(key)
}
return ret
}
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
return store.deserialize(storage.getAttribute(key))
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=0, attr; attr=attributes[i]; i++) {
storage.removeAttribute(attr.name)
}
storage.save(localStorageName)
})
store.getAll = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
var ret = {}
for (var i=0, attr; attr=attributes[i]; ++i) {
var key = ieKeyFix(attr.name)
ret[attr.name] = store.deserialize(storage.getAttribute(key))
}
return ret
})
}
try {
store.set(namespace, namespace)
if (store.get(namespace) != namespace) { store.disabled = true }
store.remove(namespace)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
if (typeof module != 'undefined' && module.exports) { module.exports = store }
else if (typeof define === 'function' && define.amd) { define(store) }
else { win.store = store }
})(this.window || global);
});
require.register("segmentio-top-domain/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var parse = require('url').parse;
/**
* Expose `domain`
*/
module.exports = domain;
/**
* RegExp
*/
var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;
/**
* Get the top domain.
*
* Official Grammar: http://tools.ietf.org/html/rfc883#page-56
* Look for tlds with up to 2-6 characters.
*
* Example:
*
* domain('http://localhost:3000/baz');
* // => ''
* domain('http://dev:3000/baz');
* // => ''
* domain('http://127.0.0.1:3000/baz');
* // => ''
* domain('http://segment.io/baz');
* // => 'segment.io'
*
* @param {String} url
* @return {String}
* @api public
*/
function domain(url){
var host = parse(url).hostname;
var match = host.match(regexp);
return match ? match[0] : '';
};
});
require.register("visionmedia-debug/index.js", function(exports, require, module){
if ('undefined' == typeof window) {
module.exports = require('./lib/debug');
} else {
module.exports = require('./debug');
}
});
require.register("visionmedia-debug/debug.js", function(exports, require, module){
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
try {
localStorage.debug = name;
} catch(e){}
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
// persist
try {
if (window.localStorage) debug.enable(localStorage.debug);
} catch(e){}
});
require.register("yields-prevent/index.js", function(exports, require, module){
/**
* prevent default on the given `e`.
*
* examples:
*
* anchor.onclick = prevent;
* anchor.onclick = function(e){
* if (something) return prevent(e);
* };
*
* @param {Event} e
*/
module.exports = function(e){
e = e || window.event
return e.preventDefault
? e.preventDefault()
: e.returnValue = false;
};
});
require.register("analytics/lib/index.js", function(exports, require, module){
/**
* Analytics.js
*
* (C) 2013 Segment.io Inc.
*/
var Integrations = require('integrations');
var Analytics = require('./analytics');
var each = require('each');
/**
* Expose the `analytics` singleton.
*/
var analytics = module.exports = exports = new Analytics();
/**
* Expose require
*/
analytics.require = require;
/**
* Expose `VERSION`.
*/
exports.VERSION = '1.5.0';
/**
* Add integrations.
*/
each(Integrations, function (name, Integration) {
analytics.use(Integration);
});
});
require.register("analytics/lib/analytics.js", function(exports, require, module){
var after = require('after');
var bind = require('bind');
var callback = require('callback');
var canonical = require('canonical');
var clone = require('clone');
var cookie = require('./cookie');
var debug = require('debug');
var defaults = require('defaults');
var each = require('each');
var Emitter = require('emitter');
var group = require('./group');
var is = require('is');
var isEmail = require('is-email');
var isMeta = require('is-meta');
var newDate = require('new-date');
var on = require('event').bind;
var prevent = require('prevent');
var querystring = require('querystring');
var size = require('object').length;
var store = require('./store');
var url = require('url');
var user = require('./user');
var Facade = require('facade');
var Identify = Facade.Identify;
var Group = Facade.Group;
var Alias = Facade.Alias;
var Track = Facade.Track;
var Page = Facade.Page;
/**
* Expose `Analytics`.
*/
module.exports = Analytics;
/**
* Initialize a new `Analytics` instance.
*/
function Analytics () {
this.Integrations = {};
this._integrations = {};
this._readied = false;
this._timeout = 300;
this._user = user; // BACKWARDS COMPATIBILITY
bind.all(this);
var self = this;
this.on('initialize', function (settings, options) {
if (options.initialPageview) self.page();
});
this.on('initialize', function () {
self._parseQuery();
});
}
/**
* Event Emitter.
*/
Emitter(Analytics.prototype);
/**
* Use a `plugin`.
*
* @param {Function} plugin
* @return {Analytics}
*/
Analytics.prototype.use = function (plugin) {
plugin(this);
return this;
};
/**
* Define a new `Integration`.
*
* @param {Function} Integration
* @return {Analytics}
*/
Analytics.prototype.addIntegration = function (Integration) {
var name = Integration.prototype.name;
if (!name) throw new TypeError('attempted to add an invalid integration');
this.Integrations[name] = Integration;
return this;
};
/**
* Initialize with the given integration `settings` and `options`. Aliased to
* `init` for convenience.
*
* @param {Object} settings
* @param {Object} options (optional)
* @return {Analytics}
*/
Analytics.prototype.init =
Analytics.prototype.initialize = function (settings, options) {
settings = settings || {};
options = options || {};
this._options(options);
this._readied = false;
this._integrations = {};
// load user now that options are set
user.load();
group.load();
// clean unknown integrations from settings
var self = this;
each(settings, function (name) {
var Integration = self.Integrations[name];
if (!Integration) delete settings[name];
});
// make ready callback
var ready = after(size(settings), function () {
self._readied = true;
self.emit('ready');
});
// initialize integrations, passing ready
each(settings, function (name, opts) {
var Integration = self.Integrations[name];
if (options.initialPageview && opts.initialPageview === false) {
Integration.prototype.page = after(2, Integration.prototype.page);
}
var integration = new Integration(clone(opts));
integration.once('ready', ready);
integration.initialize();
self._integrations[name] = integration;
});
// backwards compat with angular plugin.
// TODO: remove
this.initialized = true;
this.emit('initialize', settings, options);
return this;
};
/**
* Identify a user by optional `id` and `traits`.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.identify = function (id, traits, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = user.id();
// clone traits before we manipulate so we don't do anything uncouth, and take
// from `user` so that we carryover anonymous traits
user.identify(id, traits);
id = user.id();
traits = user.traits();
this._invoke('identify', new Identify({
options: options,
traits: traits,
userId: id
}));
// emit
this.emit('identify', id, traits, options);
this._callback(fn);
return this;
};
/**
* Return the current user.
*
* @return {Object}
*/
Analytics.prototype.user = function () {
return user;
};
/**
* Identify a group by optional `id` and `traits`. Or, if no arguments are
* supplied, return the current group.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics or Object}
*/
Analytics.prototype.group = function (id, traits, options, fn) {
if (0 === arguments.length) return group;
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = group.id();
// grab from group again to make sure we're taking from the source
group.identify(id, traits);
id = group.id();
traits = group.traits();
this._invoke('group', new Group({
options: options,
traits: traits,
groupId: id
}));
this.emit('group', id, traits, options);
this._callback(fn);
return this;
};
/**
* Track an `event` that a user has triggered with optional `properties`.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.track = function (event, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = null, properties = null;
this._invoke('track', new Track({
properties: properties,
options: options,
event: event
}));
this.emit('track', event, properties, options);
this._callback(fn);
return this;
};
/**
* Helper method to track an outbound link that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackClick`.
*
* @param {Element or Array} links
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackClick =
Analytics.prototype.trackLink = function (links, event, properties) {
if (!links) return this;
if (is.element(links)) links = [links]; // always arrays, handles jquery
var self = this;
each(links, function (el) {
on(el, 'click', function (e) {
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
if (el.href && el.target !== '_blank' && !isMeta(e)) {
prevent(e);
self._callback(function () {
window.location.href = el.href;
});
}
});
});
return this;
};
/**
* Helper method to track an outbound form that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackSubmit`.
*
* @param {Element or Array} forms
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackSubmit =
Analytics.prototype.trackForm = function (forms, event, properties) {
if (!forms) return this;
if (is.element(forms)) forms = [forms]; // always arrays, handles jquery
var self = this;
each(forms, function (el) {
function handler (e) {
prevent(e);
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
self._callback(function () {
el.submit();
});
}
// support the events happening through jQuery or Zepto instead of through
// the normal DOM API, since `el.submit` doesn't bubble up events...
var $ = window.jQuery || window.Zepto;
if ($) {
$(el).submit(handler);
} else {
on(el, 'submit', handler);
}
});
return this;
};
/**
* Trigger a pageview, labeling the current page with an optional `category`,
* `name` and `properties`.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object or String} properties (or path) (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.page = function (category, name, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = properties = null;
if (is.fn(name)) fn = name, options = properties = name = null;
if (is.object(category)) options = name, properties = category, name = category = null;
if (is.object(name)) options = properties, properties = name, name = null;
if (is.string(category) && !is.string(name)) name = category, category = null;
var defs = {
path: canonicalPath(),
referrer: document.referrer,
title: document.title,
search: location.search
};
if (name) defs.name = name;
if (category) defs.category = category;
properties = clone(properties) || {};
defaults(properties, defs);
properties.url = properties.url || canonicalUrl(properties.search);
this._invoke('page', new Page({
properties: properties,
category: category,
options: options,
name: name
}));
this.emit('page', category, name, properties, options);
this._callback(fn);
return this;
};
/**
* BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call.
*
* @param {String} url (optional)
* @param {Object} options (optional)
* @return {Analytics}
* @api private
*/
Analytics.prototype.pageview = function (url, options) {
var properties = {};
if (url) properties.path = url;
this.page(properties);
return this;
};
/**
* Merge two previously unassociated user identities.
*
* @param {String} to
* @param {String} from (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.alias = function (to, from, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(from)) fn = from, options = null, from = null;
if (is.object(from)) options = from, from = null;
this._invoke('alias', new Alias({
options: options,
from: from,
to: to
}));
this.emit('alias', to, from, options);
this._callback(fn);
return this;
};
/**
* Register a `fn` to be fired when all the analytics services are ready.
*
* @param {Function} fn
* @return {Analytics}
*/
Analytics.prototype.ready = function (fn) {
if (!is.fn(fn)) return this;
this._readied
? callback.async(fn)
: this.once('ready', fn);
return this;
};
/**
* Set the `timeout` (in milliseconds) used for callbacks.
*
* @param {Number} timeout
*/
Analytics.prototype.timeout = function (timeout) {
this._timeout = timeout;
};
/**
* Enable or disable debug.
*
* @param {String or Boolean} str
*/
Analytics.prototype.debug = function(str){
if (0 == arguments.length || str) {
debug.enable('analytics:' + (str || '*'));
} else {
debug.disable();
}
};
/**
* Apply options.
*
* @param {Object} options
* @return {Analytics}
* @api private
*/
Analytics.prototype._options = function (options) {
options = options || {};
cookie.options(options.cookie);
store.options(options.localStorage);
user.options(options.user);
group.options(options.group);
return this;
};
/**
* Callback a `fn` after our defined timeout period.
*
* @param {Function} fn
* @return {Analytics}
* @api private
*/
Analytics.prototype._callback = function (fn) {
callback.async(fn, this._timeout);
return this;
};
/**
* Call `method` with `facade` on all enabled integrations.
*
* @param {String} method
* @param {Facade} facade
* @return {Analytics}
* @api private
*/
Analytics.prototype._invoke = function (method, facade) {
var options = facade.options();
this.emit('invoke', facade);
each(this._integrations, function (name, integration) {
if (!facade.enabled(name)) return;
integration.invoke.call(integration, method, facade);
});
return this;
};
/**
* Push `args`.
*
* @param {Array} args
* @api private
*/
Analytics.prototype.push = function(args){
var method = args.shift();
if (!this[method]) return;
this[method].apply(this, args);
};
/**
* Parse the query string for callable methods.
*
* @return {Analytics}
* @api private
*/
Analytics.prototype._parseQuery = function () {
// Identify and track any `ajs_uid` and `ajs_event` parameters in the URL.
var q = querystring.parse(window.location.search);
if (q.ajs_uid) this.identify(q.ajs_uid);
if (q.ajs_event) this.track(q.ajs_event);
return this;
};
/**
* Return the canonical path for the page.
*
* @return {String}
*/
function canonicalPath () {
var canon = canonical();
if (!canon) return window.location.pathname;
var parsed = url.parse(canon);
return parsed.pathname;
}
/**
* Return the canonical URL for the page concat the given `search`
* and strip the hash.
*
* @param {String} search
* @return {String}
*/
function canonicalUrl (search) {
var canon = canonical();
if (canon) return ~canon.indexOf('?') ? canon : canon + search;
var url = window.location.href;
var i = url.indexOf('#');
return -1 == i ? url : url.slice(0, i);
}
});
require.register("analytics/lib/cookie.js", function(exports, require, module){
var bind = require('bind');
var cookie = require('cookie');
var clone = require('clone');
var defaults = require('defaults');
var json = require('json');
var topDomain = require('top-domain');
/**
* Initialize a new `Cookie` with `options`.
*
* @param {Object} options
*/
function Cookie (options) {
this.options(options);
}
/**
* Get or set the cookie options.
*
* @param {Object} options
* @field {Number} maxage (1 year)
* @field {String} domain
* @field {String} path
* @field {Boolean} secure
*/
Cookie.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
var domain = '.' + topDomain(window.location.href);
// localhost cookies are special: http://curl.haxx.se/rfc/cookie_spec.html
if ('.' == domain) domain = '';
defaults(options, {
maxage: 31536000000, // default to a year
path: '/',
domain: domain
});
this._options = options;
};
/**
* Set a `key` and `value` in our cookie.
*
* @param {String} key
* @param {Object} value
* @return {Boolean} saved
*/
Cookie.prototype.set = function (key, value) {
try {
value = json.stringify(value);
cookie(key, value, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Get a value from our cookie by `key`.
*
* @param {String} key
* @return {Object} value
*/
Cookie.prototype.get = function (key) {
try {
var value = cookie(key);
value = value ? json.parse(value) : null;
return value;
} catch (e) {
return null;
}
};
/**
* Remove a value from our cookie by `key`.
*
* @param {String} key
* @return {Boolean} removed
*/
Cookie.prototype.remove = function (key) {
try {
cookie(key, null, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Expose the cookie singleton.
*/
module.exports = bind.all(new Cookie());
/**
* Expose the `Cookie` constructor.
*/
module.exports.Cookie = Cookie;
});
require.register("analytics/lib/entity.js", function(exports, require, module){
var traverse = require('isodate-traverse');
var defaults = require('defaults');
var cookie = require('./cookie');
var store = require('./store');
var extend = require('extend');
var clone = require('clone');
/**
* Expose `Entity`
*/
module.exports = Entity;
/**
* Initialize new `Entity` with `options`.
*
* @param {Object} options
*/
function Entity(options){
this.options(options);
}
/**
* Get or set storage `options`.
*
* @param {Object} options
* @property {Object} cookie
* @property {Object} localStorage
* @property {Boolean} persist (default: `true`)
*/
Entity.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options || (options = {});
defaults(options, this.defaults || {});
this._options = options;
};
/**
* Get or set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype.id = function (id) {
switch (arguments.length) {
case 0: return this._getId();
case 1: return this._setId(id);
}
};
/**
* Get the entity's id.
*
* @return {String}
*/
Entity.prototype._getId = function () {
var ret = this._options.persist
? cookie.get(this._options.cookie.key)
: this._id;
return ret === undefined ? null : ret;
};
/**
* Set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype._setId = function (id) {
if (this._options.persist) {
cookie.set(this._options.cookie.key, id);
} else {
this._id = id;
}
};
/**
* Get or set the entity's `traits`.
*
* BACKWARDS COMPATIBILITY: aliased to `properties`
*
* @param {Object} traits
*/
Entity.prototype.properties =
Entity.prototype.traits = function (traits) {
switch (arguments.length) {
case 0: return this._getTraits();
case 1: return this._setTraits(traits);
}
};
/**
* Get the entity's traits. Always convert ISO date strings into real dates,
* since they aren't parsed back from local storage.
*
* @return {Object}
*/
Entity.prototype._getTraits = function () {
var ret = this._options.persist
? store.get(this._options.localStorage.key)
: this._traits;
return ret ? traverse(clone(ret)) : {};
};
/**
* Set the entity's `traits`.
*
* @param {Object} traits
*/
Entity.prototype._setTraits = function (traits) {
traits || (traits = {});
if (this._options.persist) {
store.set(this._options.localStorage.key, traits);
} else {
this._traits = traits;
}
};
/**
* Identify the entity with an `id` and `traits`. If we it's the same entity,
* extend the existing `traits` instead of overwriting.
*
* @param {String} id
* @param {Object} traits
*/
Entity.prototype.identify = function (id, traits) {
traits || (traits = {});
var current = this.id();
if (current === null || current === id) traits = extend(this.traits(), traits);
if (id) this.id(id);
this.debug('identify %o, %o', id, traits);
this.traits(traits);
this.save();
};
/**
* Save the entity to local storage and the cookie.
*
* @return {Boolean}
*/
Entity.prototype.save = function () {
if (!this._options.persist) return false;
cookie.set(this._options.cookie.key, this.id());
store.set(this._options.localStorage.key, this.traits());
return true;
};
/**
* Log the entity out, reseting `id` and `traits` to defaults.
*/
Entity.prototype.logout = function () {
this.id(null);
this.traits({});
cookie.remove(this._options.cookie.key);
store.remove(this._options.localStorage.key);
};
/**
* Reset all entity state, logging out and returning options to defaults.
*/
Entity.prototype.reset = function () {
this.logout();
this.options({});
};
/**
* Load saved entity `id` or `traits` from storage.
*/
Entity.prototype.load = function () {
this.id(cookie.get(this._options.cookie.key));
this.traits(store.get(this._options.localStorage.key));
};
});
require.register("analytics/lib/group.js", function(exports, require, module){
var debug = require('debug')('analytics:group');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
/**
* Group defaults
*/
Group.defaults = {
persist: true,
cookie: {
key: 'ajs_group_id'
},
localStorage: {
key: 'ajs_group_properties'
}
};
/**
* Initialize a new `Group` with `options`.
*
* @param {Object} options
*/
function Group (options) {
this.defaults = Group.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(Group, Entity);
/**
* Expose the group singleton.
*/
module.exports = bind.all(new Group());
/**
* Expose the `Group` constructor.
*/
module.exports.Group = Group;
});
require.register("analytics/lib/store.js", function(exports, require, module){
var bind = require('bind');
var defaults = require('defaults');
var store = require('store');
/**
* Initialize a new `Store` with `options`.
*
* @param {Object} options
*/
function Store (options) {
this.options(options);
}
/**
* Set the `options` for the store.
*
* @param {Object} options
* @field {Boolean} enabled (true)
*/
Store.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
defaults(options, { enabled : true });
this.enabled = options.enabled && store.enabled;
this._options = options;
};
/**
* Set a `key` and `value` in local storage.
*
* @param {String} key
* @param {Object} value
*/
Store.prototype.set = function (key, value) {
if (!this.enabled) return false;
return store.set(key, value);
};
/**
* Get a value from local storage by `key`.
*
* @param {String} key
* @return {Object}
*/
Store.prototype.get = function (key) {
if (!this.enabled) return null;
return store.get(key);
};
/**
* Remove a value from local storage by `key`.
*
* @param {String} key
*/
Store.prototype.remove = function (key) {
if (!this.enabled) return false;
return store.remove(key);
};
/**
* Expose the store singleton.
*/
module.exports = bind.all(new Store());
/**
* Expose the `Store` constructor.
*/
module.exports.Store = Store;
});
require.register("analytics/lib/user.js", function(exports, require, module){
var debug = require('debug')('analytics:user');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
var cookie = require('./cookie');
/**
* User defaults
*/
User.defaults = {
persist: true,
cookie: {
key: 'ajs_user_id',
oldKey: 'ajs_user'
},
localStorage: {
key: 'ajs_user_traits'
}
};
/**
* Initialize a new `User` with `options`.
*
* @param {Object} options
*/
function User (options) {
this.defaults = User.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(User, Entity);
/**
* Load saved user `id` or `traits` from storage.
*/
User.prototype.load = function () {
if (this._loadOldCookie()) return;
Entity.prototype.load.call(this);
};
/**
* BACKWARDS COMPATIBILITY: Load the old user from the cookie.
*
* @return {Boolean}
* @api private
*/
User.prototype._loadOldCookie = function () {
var user = cookie.get(this._options.cookie.oldKey);
if (!user) return false;
this.id(user.id);
this.traits(user.traits);
cookie.remove(this._options.cookie.oldKey);
return true;
};
/**
* Expose the user singleton.
*/
module.exports = bind.all(new User());
/**
* Expose the `User` constructor.
*/
module.exports.User = User;
});
require.register("segmentio-analytics.js-integrations/lib/slugs.json", function(exports, require, module){
module.exports = [
"adroll",
"adwords",
"alexa",
"amplitude",
"awesm",
"awesomatic",
"bing-ads",
"bronto",
"bugherd",
"bugsnag",
"chartbeat",
"churnbee",
"clicktale",
"clicky",
"comscore",
"crazy-egg",
"curebit",
"customerio",
"drip",
"errorception",
"evergage",
"facebook-ads",
"foxmetrics",
"frontleaf",
"gauges",
"get-satisfaction",
"google-analytics",
"google-tag-manager",
"gosquared",
"heap",
"hellobar",
"hittail",
"hubspot",
"improvely",
"inspectlet",
"intercom",
"keen-io",
"kenshoo",
"kissmetrics",
"klaviyo",
"leadlander",
"livechat",
"lucky-orange",
"lytics",
"mixpanel",
"mojn",
"mouseflow",
"mousestats",
"navilytics",
"olark",
"optimizely",
"perfect-audience",
"pingdom",
"piwik",
"preact",
"qualaroo",
"quantcast",
"rollbar",
"saasquatch",
"sentry",
"snapengage",
"spinnakr",
"tapstream",
"trakio",
"twitter-ads",
"usercycle",
"userfox",
"uservoice",
"vero",
"visual-website-optimizer",
"webengage",
"woopra",
"yandex-metrica"
]
});
require.alias("avetisk-defaults/index.js", "analytics/deps/defaults/index.js");
require.alias("avetisk-defaults/index.js", "defaults/index.js");
require.alias("component-clone/index.js", "analytics/deps/clone/index.js");
require.alias("component-clone/index.js", "clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-cookie/index.js", "analytics/deps/cookie/index.js");
require.alias("component-cookie/index.js", "cookie/index.js");
require.alias("component-each/index.js", "analytics/deps/each/index.js");
require.alias("component-each/index.js", "each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("component-emitter/index.js", "analytics/deps/emitter/index.js");
require.alias("component-emitter/index.js", "emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("component-event/index.js", "analytics/deps/event/index.js");
require.alias("component-event/index.js", "event/index.js");
require.alias("component-inherit/index.js", "analytics/deps/inherit/index.js");
require.alias("component-inherit/index.js", "inherit/index.js");
require.alias("component-object/index.js", "analytics/deps/object/index.js");
require.alias("component-object/index.js", "object/index.js");
require.alias("component-querystring/index.js", "analytics/deps/querystring/index.js");
require.alias("component-querystring/index.js", "querystring/index.js");
require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js");
require.alias("component-type/index.js", "component-querystring/deps/type/index.js");
require.alias("component-url/index.js", "analytics/deps/url/index.js");
require.alias("component-url/index.js", "url/index.js");
require.alias("ianstormtaylor-bind/index.js", "analytics/deps/bind/index.js");
require.alias("ianstormtaylor-bind/index.js", "bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-callback/index.js", "analytics/deps/callback/index.js");
require.alias("ianstormtaylor-callback/index.js", "callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-is/index.js", "analytics/deps/is/index.js");
require.alias("ianstormtaylor-is/index.js", "is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-after/index.js", "analytics/deps/after/index.js");
require.alias("segmentio-after/index.js", "after/index.js");
require.alias("segmentio-analytics.js-integrations/index.js", "analytics/deps/integrations/index.js");
require.alias("segmentio-analytics.js-integrations/lib/adroll.js", "analytics/deps/integrations/lib/adroll.js");
require.alias("segmentio-analytics.js-integrations/lib/adwords.js", "analytics/deps/integrations/lib/adwords.js");
require.alias("segmentio-analytics.js-integrations/lib/alexa.js", "analytics/deps/integrations/lib/alexa.js");
require.alias("segmentio-analytics.js-integrations/lib/amplitude.js", "analytics/deps/integrations/lib/amplitude.js");
require.alias("segmentio-analytics.js-integrations/lib/awesm.js", "analytics/deps/integrations/lib/awesm.js");
require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js", "analytics/deps/integrations/lib/awesomatic.js");
require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js", "analytics/deps/integrations/lib/bing-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/bronto.js", "analytics/deps/integrations/lib/bronto.js");
require.alias("segmentio-analytics.js-integrations/lib/bugherd.js", "analytics/deps/integrations/lib/bugherd.js");
require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js", "analytics/deps/integrations/lib/bugsnag.js");
require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js", "analytics/deps/integrations/lib/chartbeat.js");
require.alias("segmentio-analytics.js-integrations/lib/churnbee.js", "analytics/deps/integrations/lib/churnbee.js");
require.alias("segmentio-analytics.js-integrations/lib/clicktale.js", "analytics/deps/integrations/lib/clicktale.js");
require.alias("segmentio-analytics.js-integrations/lib/clicky.js", "analytics/deps/integrations/lib/clicky.js");
require.alias("segmentio-analytics.js-integrations/lib/comscore.js", "analytics/deps/integrations/lib/comscore.js");
require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js", "analytics/deps/integrations/lib/crazy-egg.js");
require.alias("segmentio-analytics.js-integrations/lib/curebit.js", "analytics/deps/integrations/lib/curebit.js");
require.alias("segmentio-analytics.js-integrations/lib/customerio.js", "analytics/deps/integrations/lib/customerio.js");
require.alias("segmentio-analytics.js-integrations/lib/drip.js", "analytics/deps/integrations/lib/drip.js");
require.alias("segmentio-analytics.js-integrations/lib/errorception.js", "analytics/deps/integrations/lib/errorception.js");
require.alias("segmentio-analytics.js-integrations/lib/evergage.js", "analytics/deps/integrations/lib/evergage.js");
require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js", "analytics/deps/integrations/lib/facebook-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js", "analytics/deps/integrations/lib/foxmetrics.js");
require.alias("segmentio-analytics.js-integrations/lib/frontleaf.js", "analytics/deps/integrations/lib/frontleaf.js");
require.alias("segmentio-analytics.js-integrations/lib/gauges.js", "analytics/deps/integrations/lib/gauges.js");
require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js", "analytics/deps/integrations/lib/get-satisfaction.js");
require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js", "analytics/deps/integrations/lib/google-analytics.js");
require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js", "analytics/deps/integrations/lib/google-tag-manager.js");
require.alias("segmentio-analytics.js-integrations/lib/gosquared.js", "analytics/deps/integrations/lib/gosquared.js");
require.alias("segmentio-analytics.js-integrations/lib/heap.js", "analytics/deps/integrations/lib/heap.js");
require.alias("segmentio-analytics.js-integrations/lib/hellobar.js", "analytics/deps/integrations/lib/hellobar.js");
require.alias("segmentio-analytics.js-integrations/lib/hittail.js", "analytics/deps/integrations/lib/hittail.js");
require.alias("segmentio-analytics.js-integrations/lib/hubspot.js", "analytics/deps/integrations/lib/hubspot.js");
require.alias("segmentio-analytics.js-integrations/lib/improvely.js", "analytics/deps/integrations/lib/improvely.js");
require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js", "analytics/deps/integrations/lib/inspectlet.js");
require.alias("segmentio-analytics.js-integrations/lib/intercom.js", "analytics/deps/integrations/lib/intercom.js");
require.alias("segmentio-analytics.js-integrations/lib/keen-io.js", "analytics/deps/integrations/lib/keen-io.js");
require.alias("segmentio-analytics.js-integrations/lib/kenshoo.js", "analytics/deps/integrations/lib/kenshoo.js");
require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js", "analytics/deps/integrations/lib/kissmetrics.js");
require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js", "analytics/deps/integrations/lib/klaviyo.js");
require.alias("segmentio-analytics.js-integrations/lib/leadlander.js", "analytics/deps/integrations/lib/leadlander.js");
require.alias("segmentio-analytics.js-integrations/lib/livechat.js", "analytics/deps/integrations/lib/livechat.js");
require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js", "analytics/deps/integrations/lib/lucky-orange.js");
require.alias("segmentio-analytics.js-integrations/lib/lytics.js", "analytics/deps/integrations/lib/lytics.js");
require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js", "analytics/deps/integrations/lib/mixpanel.js");
require.alias("segmentio-analytics.js-integrations/lib/mojn.js", "analytics/deps/integrations/lib/mojn.js");
require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js", "analytics/deps/integrations/lib/mouseflow.js");
require.alias("segmentio-analytics.js-integrations/lib/mousestats.js", "analytics/deps/integrations/lib/mousestats.js");
require.alias("segmentio-analytics.js-integrations/lib/navilytics.js", "analytics/deps/integrations/lib/navilytics.js");
require.alias("segmentio-analytics.js-integrations/lib/olark.js", "analytics/deps/integrations/lib/olark.js");
require.alias("segmentio-analytics.js-integrations/lib/optimizely.js", "analytics/deps/integrations/lib/optimizely.js");
require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js", "analytics/deps/integrations/lib/perfect-audience.js");
require.alias("segmentio-analytics.js-integrations/lib/pingdom.js", "analytics/deps/integrations/lib/pingdom.js");
require.alias("segmentio-analytics.js-integrations/lib/piwik.js", "analytics/deps/integrations/lib/piwik.js");
require.alias("segmentio-analytics.js-integrations/lib/preact.js", "analytics/deps/integrations/lib/preact.js");
require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js", "analytics/deps/integrations/lib/qualaroo.js");
require.alias("segmentio-analytics.js-integrations/lib/quantcast.js", "analytics/deps/integrations/lib/quantcast.js");
require.alias("segmentio-analytics.js-integrations/lib/rollbar.js", "analytics/deps/integrations/lib/rollbar.js");
require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js", "analytics/deps/integrations/lib/saasquatch.js");
require.alias("segmentio-analytics.js-integrations/lib/sentry.js", "analytics/deps/integrations/lib/sentry.js");
require.alias("segmentio-analytics.js-integrations/lib/snapengage.js", "analytics/deps/integrations/lib/snapengage.js");
require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js", "analytics/deps/integrations/lib/spinnakr.js");
require.alias("segmentio-analytics.js-integrations/lib/tapstream.js", "analytics/deps/integrations/lib/tapstream.js");
require.alias("segmentio-analytics.js-integrations/lib/trakio.js", "analytics/deps/integrations/lib/trakio.js");
require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js", "analytics/deps/integrations/lib/twitter-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/usercycle.js", "analytics/deps/integrations/lib/usercycle.js");
require.alias("segmentio-analytics.js-integrations/lib/userfox.js", "analytics/deps/integrations/lib/userfox.js");
require.alias("segmentio-analytics.js-integrations/lib/uservoice.js", "analytics/deps/integrations/lib/uservoice.js");
require.alias("segmentio-analytics.js-integrations/lib/vero.js", "analytics/deps/integrations/lib/vero.js");
require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", "analytics/deps/integrations/lib/visual-website-optimizer.js");
require.alias("segmentio-analytics.js-integrations/lib/webengage.js", "analytics/deps/integrations/lib/webengage.js");
require.alias("segmentio-analytics.js-integrations/lib/woopra.js", "analytics/deps/integrations/lib/woopra.js");
require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js", "analytics/deps/integrations/lib/yandex-metrica.js");
require.alias("segmentio-analytics.js-integrations/index.js", "integrations/index.js");
require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integrations/deps/defaults/index.js");
require.alias("component-clone/index.js", "segmentio-analytics.js-integrations/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-domify/index.js", "segmentio-analytics.js-integrations/deps/domify/index.js");
require.alias("component-each/index.js", "segmentio-analytics.js-integrations/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("component-once/index.js", "segmentio-analytics.js-integrations/deps/once/index.js");
require.alias("component-type/index.js", "segmentio-analytics.js-integrations/deps/type/index.js");
require.alias("component-url/index.js", "segmentio-analytics.js-integrations/deps/url/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integrations/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integrations/deps/bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-analytics.js-integrations/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "segmentio-analytics.js-integrations/deps/is-empty/index.js");
require.alias("segmentio-alias/index.js", "segmentio-analytics.js-integrations/deps/alias/index.js");
require.alias("component-clone/index.js", "segmentio-alias/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-type/index.js", "segmentio-alias/deps/type/index.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/lib/index.js");
require.alias("segmentio-analytics.js-integration/lib/protos.js", "segmentio-analytics.js-integrations/deps/integration/lib/protos.js");
require.alias("segmentio-analytics.js-integration/lib/events.js", "segmentio-analytics.js-integrations/deps/integration/lib/events.js");
require.alias("segmentio-analytics.js-integration/lib/statics.js", "segmentio-analytics.js-integrations/deps/integration/lib/statics.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/index.js");
require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js");
require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "segmentio-analytics.js-integration/deps/to-no-case/index.js");
require.alias("component-type/index.js", "segmentio-analytics.js-integration/deps/type/index.js");
require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js");
require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js");
require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js");
require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js");
require.alias("segmentio-canonical/index.js", "segmentio-analytics.js-integrations/deps/canonical/index.js");
require.alias("segmentio-convert-dates/index.js", "segmentio-analytics.js-integrations/deps/convert-dates/index.js");
require.alias("component-clone/index.js", "segmentio-convert-dates/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-convert-dates/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-extend/index.js", "segmentio-analytics.js-integrations/deps/extend/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/lib/index.js");
require.alias("segmentio-facade/lib/alias.js", "segmentio-analytics.js-integrations/deps/facade/lib/alias.js");
require.alias("segmentio-facade/lib/facade.js", "segmentio-analytics.js-integrations/deps/facade/lib/facade.js");
require.alias("segmentio-facade/lib/group.js", "segmentio-analytics.js-integrations/deps/facade/lib/group.js");
require.alias("segmentio-facade/lib/page.js", "segmentio-analytics.js-integrations/deps/facade/lib/page.js");
require.alias("segmentio-facade/lib/identify.js", "segmentio-analytics.js-integrations/deps/facade/lib/identify.js");
require.alias("segmentio-facade/lib/is-enabled.js", "segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js");
require.alias("segmentio-facade/lib/track.js", "segmentio-analytics.js-integrations/deps/facade/lib/track.js");
require.alias("segmentio-facade/lib/screen.js", "segmentio-analytics.js-integrations/deps/facade/lib/screen.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/index.js");
require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js");
require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js");
require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js");
require.alias("segmentio-global-queue/index.js", "segmentio-analytics.js-integrations/deps/global-queue/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-analytics.js-integrations/deps/is-email/index.js");
require.alias("segmentio-load-date/index.js", "segmentio-analytics.js-integrations/deps/load-date/index.js");
require.alias("segmentio-load-script/index.js", "segmentio-analytics.js-integrations/deps/load-script/index.js");
require.alias("component-type/index.js", "segmentio-load-script/deps/type/index.js");
require.alias("segmentio-script-onload/index.js", "segmentio-analytics.js-integrations/deps/script-onload/index.js");
require.alias("segmentio-script-onload/index.js", "segmentio-analytics.js-integrations/deps/script-onload/index.js");
require.alias("segmentio-script-onload/index.js", "segmentio-script-onload/index.js");
require.alias("segmentio-on-body/index.js", "segmentio-analytics.js-integrations/deps/on-body/index.js");
require.alias("component-each/index.js", "segmentio-on-body/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("segmentio-on-error/index.js", "segmentio-analytics.js-integrations/deps/on-error/index.js");
require.alias("segmentio-to-iso-string/index.js", "segmentio-analytics.js-integrations/deps/to-iso-string/index.js");
require.alias("segmentio-to-unix-timestamp/index.js", "segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js");
require.alias("segmentio-use-https/index.js", "segmentio-analytics.js-integrations/deps/use-https/index.js");
require.alias("segmentio-when/index.js", "segmentio-analytics.js-integrations/deps/when/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-when/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integrations/deps/next-tick/index.js");
require.alias("yields-slug/index.js", "segmentio-analytics.js-integrations/deps/slug/index.js");
require.alias("visionmedia-batch/index.js", "segmentio-analytics.js-integrations/deps/batch/index.js");
require.alias("component-emitter/index.js", "visionmedia-batch/deps/emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integrations/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integrations/deps/debug/debug.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js");
require.alias("component-querystring/index.js", "segmentio-load-pixel/deps/querystring/index.js");
require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js");
require.alias("component-type/index.js", "component-querystring/deps/type/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-substitute/index.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-load-pixel/index.js");
require.alias("segmentio-replace-document-write/index.js", "segmentio-analytics.js-integrations/deps/replace-document-write/index.js");
require.alias("segmentio-replace-document-write/index.js", "segmentio-analytics.js-integrations/deps/replace-document-write/index.js");
require.alias("component-domify/index.js", "segmentio-replace-document-write/deps/domify/index.js");
require.alias("segmentio-replace-document-write/index.js", "segmentio-replace-document-write/index.js");
require.alias("component-indexof/index.js", "segmentio-analytics.js-integrations/deps/indexof/index.js");
require.alias("component-object/index.js", "segmentio-analytics.js-integrations/deps/object/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-analytics.js-integrations/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-analytics.js-integrations/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-canonical/index.js", "analytics/deps/canonical/index.js");
require.alias("segmentio-canonical/index.js", "canonical/index.js");
require.alias("segmentio-extend/index.js", "analytics/deps/extend/index.js");
require.alias("segmentio-extend/index.js", "extend/index.js");
require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/lib/index.js");
require.alias("segmentio-facade/lib/alias.js", "analytics/deps/facade/lib/alias.js");
require.alias("segmentio-facade/lib/facade.js", "analytics/deps/facade/lib/facade.js");
require.alias("segmentio-facade/lib/group.js", "analytics/deps/facade/lib/group.js");
require.alias("segmentio-facade/lib/page.js", "analytics/deps/facade/lib/page.js");
require.alias("segmentio-facade/lib/identify.js", "analytics/deps/facade/lib/identify.js");
require.alias("segmentio-facade/lib/is-enabled.js", "analytics/deps/facade/lib/is-enabled.js");
require.alias("segmentio-facade/lib/track.js", "analytics/deps/facade/lib/track.js");
require.alias("segmentio-facade/lib/screen.js", "analytics/deps/facade/lib/screen.js");
require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/index.js");
require.alias("segmentio-facade/lib/index.js", "facade/index.js");
require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js");
require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js");
require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js");
require.alias("segmentio-is-email/index.js", "analytics/deps/is-email/index.js");
require.alias("segmentio-is-email/index.js", "is-email/index.js");
require.alias("segmentio-is-meta/index.js", "analytics/deps/is-meta/index.js");
require.alias("segmentio-is-meta/index.js", "is-meta/index.js");
require.alias("segmentio-isodate-traverse/index.js", "analytics/deps/isodate-traverse/index.js");
require.alias("segmentio-isodate-traverse/index.js", "isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("segmentio-json/index.js", "analytics/deps/json/index.js");
require.alias("segmentio-json/index.js", "json/index.js");
require.alias("component-json-fallback/index.js", "segmentio-json/deps/json-fallback/index.js");
require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "analytics/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "analytics/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/index.js");
require.alias("segmentio-new-date/lib/index.js", "new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/store.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/index.js");
require.alias("segmentio-store.js/store.js", "store/index.js");
require.alias("segmentio-store.js/store.js", "segmentio-store.js/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "top-domain/index.js");
require.alias("component-url/index.js", "segmentio-top-domain/deps/url/index.js");
require.alias("segmentio-top-domain/index.js", "segmentio-top-domain/index.js");
require.alias("visionmedia-debug/index.js", "analytics/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "analytics/deps/debug/debug.js");
require.alias("visionmedia-debug/index.js", "debug/index.js");
require.alias("yields-prevent/index.js", "analytics/deps/prevent/index.js");
require.alias("yields-prevent/index.js", "prevent/index.js");
require.alias("analytics/lib/index.js", "analytics/index.js");if (typeof exports == "object") {
module.exports = require("analytics");
} else if (typeof define == "function" && define.amd) {
define([], function(){ return require("analytics"); });
} else {
this["analytics"] = require("analytics");
}})(); |
frontend/app_v2/src/common/icons/Word.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
/**
* @summary Word
* @component
*
* @param {object} props
*
* @returns {node} jsx markup
*/
function Word({ styling }) {
return (
<svg data-testid="Word" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className={styling}>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z" />
</svg>
)
}
// PROPTYPES
const { string } = PropTypes
Word.propTypes = {
styling: string,
}
export default Word
|
fields/types/datearray/DateArrayFilter.js | tony2cssc/keystone | import React from 'react';
import ReactDOM from 'react-dom';
import moment from 'moment';
import DayPicker from 'react-day-picker';
import { FormField, FormInput, FormRow, FormSelect } from 'elemental';
const PRESENCE_OPTIONS = [
{ label: 'At least one element', value: 'some' },
{ label: 'No element', value: 'none' },
];
const MODE_OPTIONS = [
{ label: 'On', value: 'on' },
{ label: 'After', value: 'after' },
{ label: 'Before', value: 'before' },
{ label: 'Between', value: 'between' },
];
var DayPickerIndicator = React.createClass({
render () {
return (
<span className="DayPicker-Indicator">
<span className="DayPicker-Indicator__border" />
<span className="DayPicker-Indicator__bg" />
</span>
);
},
});
function getDefaultValue () {
return {
mode: MODE_OPTIONS[0].value,
presence: PRESENCE_OPTIONS[0].value,
value: moment(0, 'HH').format(),
before: moment(0, 'HH').format(),
after: moment(0, 'HH').format(),
};
}
var DateFilter = React.createClass({
displayName: 'DateFilter',
propTypes: {
filter: React.PropTypes.shape({
mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)),
presence: React.PropTypes.string,
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
format: 'DD-MM-YYYY',
filter: getDefaultValue(),
value: moment().startOf('day').toDate(),
};
},
getInitialState () {
return {
activeInputField: 'after',
month: new Date(), // The month to display in the calendar
};
},
componentDidMount () {
// focus the text input
if (this.props.filter.mode === 'between') {
ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus();
} else {
ReactDOM.findDOMNode(this.refs.input).focus();
}
},
updateFilter (value) {
this.props.onChange({ ...this.props.filter, ...value });
},
selectPresence (presence) {
this.updateFilter({ presence });
ReactDOM.findDOMNode(this.refs.input).focus();
},
selectMode (mode) {
this.updateFilter({ mode });
if (mode === 'between') {
setTimeout(() => { ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus(); }, 200);
} else {
ReactDOM.findDOMNode(this.refs.input).focus();
}
},
handleInputChange (e) {
const { value } = e.target;
let { month } = this.state;
// Change the current month only if the value entered by the user is a valid
// date, according to the `L` format
if (moment(value, 'L', true).isValid()) {
month = moment(value, 'L').toDate();
}
this.updateFilter({ value: value });
this.setState({ month }, this.showCurrentDate);
},
setActiveField (field) {
this.setState({
activeInputField: field,
});
},
switchBetweenActiveInputFields (e, day, modifiers) {
if (modifiers.indexOf('disabled') > -1) return;
const { activeInputField } = this.state;
const send = {};
send[activeInputField] = day;
this.updateFilter(send);
const newActiveField = (activeInputField === 'before') ? 'after' : 'before';
this.setState(
{ activeInputField: newActiveField },
() => {
ReactDOM.findDOMNode(this.refs[newActiveField]).focus();
}
);
},
selectDay (e, day, modifiers) {
if (modifiers.indexOf('disabled') > -1) return;
this.updateFilter({ value: day });
},
showCurrentDate () {
this.refs.daypicker.showMonth(this.state.month);
},
renderControls () {
let controls;
const { field, filter } = this.props;
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...';
// DayPicker stuff
const modifiers = {
selected: (day) => moment(filter.value).isSame(day),
};
if (mode.value === 'between') {
controls = (
<div>
<FormRow>
<FormField width="one-half">
<FormInput ref="after" placeholder="From" onFocus={(e) => { this.setActiveField('after'); }} value={moment(filter.after).format(this.props.format)} />
</FormField>
<FormField width="one-half">
<FormInput ref="before" placeholder="To" onFocus={(e) => { this.setActiveField('before'); }} value={moment(filter.before).format(this.props.format)} />
</FormField>
</FormRow>
<div style={{ position: 'relative' }}>
<DayPicker
modifiers={modifiers}
className="DayPicker--chrome"
onDayClick={this.switchBetweenActiveInputFields}
/>
<DayPickerIndicator />
</div>
</div>
);
} else {
controls = (
<div>
<FormField>
<FormInput
ref="input"
placeholder={placeholder}
value={moment(filter.value).format(this.props.format)}
onChange={this.handleInputChange}
onFocus={this.showCurrentDate}
/>
</FormField>
<div style={{ position: 'relative' }}>
<DayPicker
ref="daypicker"
modifiers={modifiers}
className="DayPicker--chrome"
onDayClick={this.selectDay}
/>
<DayPickerIndicator />
</div>
</div>
);
}
return controls;
},
render () {
const { filter } = this.props;
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0];
return (
<div>
<FormSelect options={PRESENCE_OPTIONS} onChange={this.selectPresence} value={presence.value} />
<FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={mode.value} />
{this.renderControls()}
</div>
);
},
});
module.exports = DateFilter;
|
src/svg-icons/editor/format-indent-decrease.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatIndentDecrease = (props) => (
<SvgIcon {...props}>
<path d="M11 17h10v-2H11v2zm-8-5l4 4V8l-4 4zm0 9h18v-2H3v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/>
</SvgIcon>
);
EditorFormatIndentDecrease = pure(EditorFormatIndentDecrease);
EditorFormatIndentDecrease.displayName = 'EditorFormatIndentDecrease';
EditorFormatIndentDecrease.muiName = 'SvgIcon';
export default EditorFormatIndentDecrease;
|
test/react_test.js | SteveTseng/slick | 'use strict';
// import { mocha } from 'mocha';
import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import Slick from '../../src/main.jsx';
describe('Slick main app' , function() {
it('calls componentDidMount', () => {
const wrapper = mount(<Slick />);
expect(Slick.prototype.componentDidMount.calledOnce).to.equal(true);
});
});
|
app/components/Tab/index.js | seanng/jobmaster-web | /**
*
* Tab
*
*/
import React from 'react';
import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
function Tab({title, clickTab, view}) {
const Span = title === view ? styled.span`
color: black;
font-weight: 600;
` : styled.span`
color: gray;
cursor: pointer;
`
return (
<Span
onClick={clickTab.bind(this, title)}
>
<FormattedMessage {...messages[title]} />
</Span>
);
}
Tab.propTypes = {
};
export default Tab;
|
packages/material-ui-icons/src/PublishOutlined.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M5 4h14v2H5zm0 10h4v6h6v-6h4l-7-7-7 7zm8-2v6h-2v-6H9.83L12 9.83 14.17 12H13z" />
, 'PublishOutlined');
|
react-express-single/client/src/index.js | rob-blackbourn/scratch-js | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
ajax/libs/6to5/2.0.0/browser.js | alexmojaki/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(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.11.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,curPosition()]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};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>=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,inType;var metParenL;var templates;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 _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};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 _arrow={type:"=>",beforeExpr:true},_template={type:"template"},_templateContinued={type:"templateContinued"};var _ellipsis={type:"...",prefix:true,beforeExpr:true};var _paamayimNekudotayim={type:"::",beforeExpr:true};var _at={type:"@"};var _hash={type:"#"};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,paamayimNekudotayim:_paamayimNekudotayim,exponent:_exponent,at:_at,hash:_hash,template:_template,templateContinued:_templateContinued};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 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 decimalNumber=/^\d+$/;var hexNumber=/^[\da-fA-F]+$/;var newline=/[\n\r\u2028\u2029]/;function isNewLine(code){return code===10||code===13||code===8232||code==8233}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(line,col){this.line=line;this.column=col}Position.prototype.offset=function(n){return new Position(this.line,this.column+n)};function curPosition(){return new Position(tokCurLine,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;inType=inXJSChild=inXJSTag=false;templates=[];if(tokPos===0&&options.allowHashBang&&input.slice(0,2)==="#!"){skipLineComment(2)}}function finishToken(type,val,shouldSkipSpace){tokEnd=tokPos;if(options.locations)tokEndLoc=curPosition();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&&curPosition();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&&curPosition())}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&curPosition();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&&curPosition())}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.playground&&next===63){tokPos+=2;return finishToken(_dotQuestion)}else 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(!inType&&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)}}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;if(templates.length)++templates[templates.length-1];return finishToken(_braceL);case 125:++tokPos;if(templates.length&&--templates[templates.length-1]===0)return readTemplateString(_templateContinued);else return finishToken(_braceR);case 63:++tokPos;return finishToken(_question);case 64:if(options.playground){++tokPos;return finishToken(_at)}case 35:if(options.playground){++tokPos;return finishToken(_hash)}case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_paamayimNekudotayim)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return readTemplateString(_template)}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=curPosition();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(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 readTemplateString(type){if(type==_templateContinued)templates.pop();var out="",start=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated template");var ch=input.charAt(tokPos);if(ch==="`"||ch==="$"&&input.charCodeAt(tokPos+1)===123){var raw=input.slice(start,tokPos);++tokPos;if(ch=="$"){++tokPos;templates.push(1)}return finishToken(type,{cooked:out,raw:raw})}if(ch==="\\"){out+=readEscapedChar()}else{++tokPos;if(newline.test(ch)){if(ch==="\r"&&input.charCodeAt(tokPos)===10){++tokPos;ch="\n"}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=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");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}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&"e!==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 finishNodeAt(node,type,pos){if(options.locations){node.loc.end=pos[1];pos=pos[0]}node.type=type;node.end=pos;if(options.ranges)node.range[1]=pos;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 ":"Assigning to ")+expr.name+" in strict mode");break;case"MemberExpression":if(isBinding)raise(expr.start,"Binding to member expression");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(true);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(topLevel){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 _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:case _import:if(!topLevel&&!options.allowImportExportEverywhere)raise(tokStart,"'import' and 'export' may only appear at the top level");return starttype===_import?parseImport(node):parseExport(node);default:var maybeName=tokVal,expr=parseExpression();if(starttype===_name){if(expr.type==="FunctionExpression"&&expr.async){expr.type="FunctionDeclaration";return expr}else if(expr.type==="Identifier"){if(eat(_colon)){return parseLabeledStatement(node,maybeName,expr)}if(options.ecmaVersion>=7&&expr.name==="private"&&tokType===_name){return parsePrivate(node)}else if(expr.name==="declare"){if(tokType===_class||tokType===_name||tokType===_function||tokType===_var){return parseDeclare(node)}}else if(tokType===_name){if(expr.name==="interface"){return parseInterface(node)}else if(expr.name==="type"){return parseTypeAlias(node)}}}}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();if(options.ecmaVersion>=6)eat(_semi);else 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 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);if(tokType===_colon){decl.id.typeAnnotation=parseTypeAnnotation();finishNode(decl.id,decl.id.type)}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,noLess){var start=storeCurrentPos();var left=parseMaybeConditional(noIn,noLess);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,noLess){var start=storeCurrentPos();var expr=parseExprOps(noIn,noLess);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,noLess){var start=storeCurrentPos();return parseExprOp(parseMaybeUnary(),start,-1,noIn,noLess)}function parseExprOp(left,leftStart,minPrec,noIn,noLess){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)&&(!noLess||tokType!==_lt)){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(_hash)){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(_paamayimNekudotayim)){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===_template){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 _at:var node=startNode();next();node.object={type:"ThisExpression"};node.property=parseExprSubscripts();node.computed=false;return finishNode(node,"MemberExpression");case _yield:if(inGenerator)return parseYield();case _name:var start=storeCurrentPos();var node=startNode();var id=parseIdent(tokType!==_name);if(options.ecmaVersion>=7){if(id.name==="async"){if(tokType===_parenL){next();var oldParenL=++metParenL;if(tokType!==_parenR){val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){return parseArrowExpression(node,exprList,true)}else{node.callee=id;node.arguments=exprList;return parseSubscripts(finishNode(node,"CallExpression"),start)}}else if(tokType===_name){id=parseIdent();if(eat(_arrow)){return parseArrowExpression(node,[id],true)}return id}if(tokType===_function){next();return parseFunction(node,false,true)}}else if(id.name==="await"){if(inAsync)return parseAwait(node)}}if(eat(_arrow)){return parseArrowExpression(node,[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 _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _template:return parseTemplate();case _lt:return parseXJSElement();case _hash: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 parseTemplateElement(){var elem=startNodeAt(options.locations?[tokStart+1,tokStartLoc.offset(1)]:tokStart+1);elem.value=tokVal;elem.tail=input.charCodeAt(tokEnd-1)!==123;next();var endOff=elem.tail?1:2;return finishNodeAt(elem,"TemplateElement",options.locations?[lastEnd-endOff,lastEndLoc.offset(-endOff)]:lastEnd-endOff)}function parseTemplate(){var node=startNode();node.expressions=[];var curElt=parseTemplateElement();node.quasis=[curElt];while(!curElt.tail){node.expressions.push(parseExpression());if(tokType!==_templateContinued)unexpected();node.quasis.push(curElt=parseTemplateElement())}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=false,isAsync=false;if(options.ecmaVersion>=7&&tokType===_ellipsis){prop=parseMaybeUnary();prop.type="SpreadProperty";node.properties.push(prop);continue}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;isGenerator=eat(_star)}if(options.ecmaVersion>=7&&tokType===_name&&tokVal==="async"){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){prop.key=asyncId}else{isAsync=true;parsePropertyName(prop)}}else{parsePropertyName(prop)}var typeParameters;if(tokType===_lt){typeParameters=parseTypeParameterDeclaration();if(tokType!==_parenL)unexpected()}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"||options.playground&&prop.key.name==="memo")){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();prop.value.typeParameters=typeParameters;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){node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}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"&¶m.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);parseFunctionParam(node.rest);expect(_parenR);defaults.push(null);break}else{var param=options.ecmaVersion>=6?toAssignable(parseExprAtom(),false,true):parseIdent();parseFunctionParam(param);node.params.push(param);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;if(tokType===_colon){node.returnType=parseTypeAnnotation()}}function parseFunctionParam(param){if(tokType===_colon){param.typeAnnotation=parseTypeAnnotation()}else if(eat(_question)){param.optional=true}finishNode(param,param.type)}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 parsePrivate(node){node.declarations=[];do{node.declarations.push(parseIdent())}while(eat(_comma));semicolon();return finishNode(node,"PrivateDeclaration")}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}node.superClass=eat(_extends)?parseMaybeAssign(false,true):null;if(node.superClass&&tokType===_lt){node.superTypeParameters=parseTypeParameterInstantiation()}if(tokType===_name&&tokVal==="implements"){next();node.implements=parseClassImplements()}var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){var method=startNode();if(options.ecmaVersion>=7&&tokType===_name&&tokVal==="private"){next();classBody.body.push(parsePrivate(method));continue}if(tokType===_name&&tokVal==="static"){next();method["static"]=true}else{method["static"]=false}var isAsync=false;var isGenerator=eat(_star);if(options.ecmaVersion>=7&&!isGenerator&&tokType===_name&&tokVal==="async"){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){method.key=asyncId}else{isAsync=true;parsePropertyName(method)}}else{parsePropertyName(method)}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set"||options.playground&&method.key.name==="memo")){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}if(tokType===_colon){if(isGenerator||isAsync)unexpected();method.typeAnnotation=parseTypeAnnotation();semicolon();classBody.body.push(finishNode(method,"ClassProperty"))}else{var typeParameters;if(tokType===_lt){typeParameters=parseTypeParameterDeclaration()}method.value=parseMethod(isGenerator,isAsync);method.value.typeParameters=typeParameters;classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseClassImplements(){var implemented=[];do{var node=startNode();node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}implemented.push(finishNode(node,"ClassImplements"))}while(eat(_comma));return implemented}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===_name&&tokVal==="async"){node.declaration=parseStatement();node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){var declar=node.declaration=parseExpression(true);if(declar.id){if(declar.type==="FunctionExpression"){declar.type="FunctionDeclaration"}else if(declar.type==="ClassExpression"){declar.type="ClassDeclaration"}}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()}else{node.specifiers=parseImportSpecifiers();if(tokType!==_name||tokVal!=="from")unexpected();next();node.source=tokType===_string?parseExprAtom():unexpected()}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_name){var node=startNode();node.id=startNode();node.name=parseIdent();checkLVal(node.name,true);node.id.name="default";finishNode(node.id,"Identifier");nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}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}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(node){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")}function parseDeclareClass(node){next();parseInterfaceish(node,true);return finishNode(node,"DeclareClass")}function parseDeclareFunction(node){next();var id=node.id=parseIdent();var typeNode=startNode();var typeContainer=startNode();if(tokType===_lt){typeNode.typeParameters=parseTypeParameterDeclaration()}else{typeNode.typeParameters=null}expect(_parenL);var tmp=parseFunctionTypeParams();typeNode.params=tmp.params;typeNode.rest=tmp.rest;expect(_parenR);expect(_colon);typeNode.returnType=parseType();typeContainer.typeAnnotation=finishNode(typeNode,"FunctionTypeAnnotation");id.typeAnnotation=finishNode(typeContainer,"TypeAnnotation");finishNode(id,id.type);semicolon();return finishNode(node,"DeclareFunction")}function parseDeclare(node){if(tokType===_class){return parseDeclareClass(node)}else if(tokType===_function){return parseDeclareFunction(node)}else if(tokType===_var){return parseDeclareVariable(node)}else if(tokType===_name&&tokVal==="module"){return parseDeclareModule(node)}else{unexpected()}}function parseDeclareVariable(node){next();node.id=parseTypeAnnotatableIdentifier();semicolon();return finishNode(node,"DeclareVariable")}function parseDeclareModule(node){next();if(tokType===_string){node.id=parseExprAtom()}else{node.id=parseIdent()}var bodyNode=node.body=startNode();var body=bodyNode.body=[];expect(_braceL);while(tokType!==_braceR){var node2=startNode();next();body.push(parseDeclare(node2))}expect(_braceR);finishNode(bodyNode,"BlockStatement");return finishNode(node,"DeclareModule")}function parseInterfaceish(node,allowStatic){node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}node.extends=[];if(eat(_extends)){do{node.extends.push(parseInterfaceExtends())}while(eat(_comma))}node.body=parseObjectType(allowStatic)}function parseInterfaceExtends(){var node=startNode();node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}return finishNode(node,"InterfaceExtends")}function parseInterface(node){parseInterfaceish(node,false);return finishNode(node,"InterfaceDeclaration")}function parseTypeAlias(node){node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}expect(_eq);node.right=parseType();semicolon();return finishNode(node,"TypeAlias")}function parseTypeParameterDeclaration(){var node=startNode();node.params=[];expect(_lt);while(tokType!==_gt){node.params.push(parseIdent());if(tokType!==_gt){expect(_comma)}}expect(_gt);return finishNode(node,"TypeParameterDeclaration")}function parseTypeParameterInstantiation(){var node=startNode(),oldInType=inType;node.params=[];inType=true;expect(_lt);while(tokType!==_gt){node.params.push(parseType());if(tokType!==_gt){expect(_comma)}}expect(_gt);inType=oldInType;return finishNode(node,"TypeParameterInstantiation")}function parseObjectPropertyKey(){return tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function parseObjectTypeIndexer(node,isStatic){node.static=isStatic;expect(_bracketL);node.id=parseObjectPropertyKey();expect(_colon);node.key=parseType();expect(_bracketR);expect(_colon);node.value=parseType();return finishNode(node,"ObjectTypeIndexer")}function parseObjectTypeMethodish(node){node.params=[];node.rest=null;node.typeParameters=null;if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}expect(_parenL);while(tokType===_name){node.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){node.rest=parseFunctionTypeParam()}expect(_parenR);expect(_colon);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}function parseObjectTypeMethod(start,isStatic,key){var node=startNodeAt(start);node.value=parseObjectTypeMethodish(startNodeAt(start));node.static=isStatic;node.key=key;node.optional=false;return finishNode(node,"ObjectTypeProperty")}function parseObjectTypeCallProperty(node,isStatic){var valueNode=startNode();node.static=isStatic;node.value=parseObjectTypeMethodish(valueNode);return finishNode(node,"ObjectTypeCallProperty")}function parseObjectType(allowStatic){var nodeStart=startNode();var node;var optional=false;var property;var propertyKey;var propertyTypeAnnotation;var token;var isStatic;nodeStart.callProperties=[];nodeStart.properties=[];nodeStart.indexers=[];expect(_braceL);while(tokType!==_braceR){var start=storeCurrentPos();node=startNode();if(allowStatic&&tokType===_name&&tokVal==="static"){next();isStatic=true}if(tokType===_bracketL){nodeStart.indexers.push(parseObjectTypeIndexer(node,isStatic))}else if(tokType===_parenL||tokType===_lt){nodeStart.callProperties.push(parseObjectTypeCallProperty(node,allowStatic))}else{if(isStatic&&tokType===_colon){propertyKey=parseIdent()}else{propertyKey=parseObjectPropertyKey()}if(tokType===_lt||tokType===_parenL){nodeStart.properties.push(parseObjectTypeMethod(start,isStatic,propertyKey))}else{if(eat(_question)){optional=true}expect(_colon);node.key=propertyKey;node.value=parseType();node.optional=optional;node.static=isStatic;nodeStart.properties.push(finishNode(node,"ObjectTypeProperty"))}}if(!eat(_semi)&&tokType!==_braceR){unexpected()}}expect(_braceR);return finishNode(nodeStart,"ObjectTypeAnnotation")}function parseGenericType(start,id){var node=startNodeAt(start);node.typeParameters=null;node.id=id;while(eat(_dot)){var node2=startNodeAt(start);node2.qualification=node.id;node2.id=parseIdent();node.id=finishNode(node2,"QualifiedTypeIdentifier")}if(tokType===_lt){node.typeParameters=parseTypeParameterInstantiation()}return finishNode(node,"GenericTypeAnnotation")}function parseVoidType(){var node=startNode();expect(keywordTypes["void"]);return finishNode(node,"VoidTypeAnnotation")}function parseTypeofType(){var node=startNode();expect(keywordTypes["typeof"]);node.argument=parsePrimaryType();return finishNode(node,"TypeofTypeAnnotation")}function parseTupleType(){var node=startNode();node.types=[];expect(_bracketL);while(tokPos<inputLen&&tokType!==_bracketR){node.types.push(parseType());if(tokType===_bracketR)break;expect(_comma)}expect(_bracketR);return finishNode(node,"TupleTypeAnnotation")}function parseFunctionTypeParam(){var optional=false;var node=startNode();node.name=parseIdent();if(eat(_question)){optional=true}expect(_colon);node.optional=optional;node.typeAnnotation=parseType();return finishNode(node,"FunctionTypeParam")}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(tokType===_name){ret.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){ret.rest=parseFunctionTypeParam()}return ret}function identToTypeAnnotation(start,node,id){switch(id.name){case"any":return finishNode(node,"AnyTypeAnnotation");case"bool":case"boolean":return finishNode(node,"BooleanTypeAnnotation");case"number":return finishNode(node,"NumberTypeAnnotation");case"string":return finishNode(node,"StringTypeAnnotation");default:return parseGenericType(start,id)}}function parsePrimaryType(){var typeIdentifier=null;var params=null;var returnType=null;var start=storeCurrentPos();var node=startNode();var rest=null;var tmp;var typeParameters;var token;var type;var isGroupedType=false;switch(tokType){case _name:return identToTypeAnnotation(start,node,parseIdent());case _braceL:return parseObjectType();case _bracketL:return parseTupleType();case _lt:node.typeParameters=parseTypeParameterDeclaration();expect(_parenL);tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation");case _parenL:next();var tmpId;if(tokType!==_parenR&&tokType!==_ellipsis){if(tokType===_name){}else{isGroupedType=true}}if(isGroupedType){if(tmpId&&_parenR){type=tmpId}else{type=parseType();expect(_parenR)}if(eat(_arrow)){raise(node,"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType")}return type}tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();node.typeParameters=null;return finishNode(node,"FunctionTypeAnnotation");case _string:node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"StringLiteralTypeAnnotation");default:if(tokType.keyword){switch(tokType.keyword){case"void":return parseVoidType();case"typeof":return parseTypeofType()}}}unexpected()}function parsePostfixType(){var node=startNode();var type=node.elementType=parsePrimaryType();if(tokType===_bracketL){expect(_bracketL);expect(_bracketR);return finishNode(node,"ArrayTypeAnnotation")}return type}function parsePrefixType(){var node=startNode();if(eat(_question)){node.typeAnnotation=parsePrefixType();return finishNode(node,"NullableTypeAnnotation")}return parsePostfixType()}function parseIntersectionType(){var node=startNode();var type=parsePrefixType();node.types=[type];while(eat(_bitwiseAND)){node.types.push(parsePrefixType())}return node.types.length===1?type:finishNode(node,"IntersectionTypeAnnotation")}function parseUnionType(){var node=startNode();var type=parseIntersectionType();node.types=[type];while(eat(_bitwiseOR)){node.types.push(parseIntersectionType())}return node.types.length===1?type:finishNode(node,"UnionTypeAnnotation")}function parseType(){var oldInType=inType;inType=true;var type=parseUnionType();inType=oldInType;return type}function parseTypeAnnotation(){var node=startNode();expect(_colon);node.typeAnnotation=parseType();return finishNode(node,"TypeAnnotation")}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var node=startNode();var ident=parseIdent();var isOptionalParam=false;if(canBeOptionalParam&&eat(_question)){expect(_question);isOptionalParam=true}if(requireTypeAnnotation||tokType===_colon){ident.typeAnnotation=parseTypeAnnotation();finishNode(ident,ident.type)}if(isOptionalParam){ident.optional=true;finishNode(ident,ident.type)}return ident}})},{}],2:[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":31}],3:[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=["inherits","prototype-properties","apply-constructor","tagged-template-literal","interop-require","to-array","object-without-properties","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,ast: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 "+JSON.stringify(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.addCode=function(code){code=(code||"")+"";this.code=code;return this.parseShebang(code)};File.prototype.parse=function(code){var self=this;code=this.addCode(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;var result={code:"",map:null,ast:null};if(opts.ast)result.ast=ast;if(!opts.code)return result;var _result=generate(ast,opts,this.code);result.code=_result.code;result.map=_result.map;if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}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":5,"./transformation/transform":31,"./traverse/scope":69,"./types":72,"./util":74,lodash:121}],4:[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(){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.format.compact)return;if(_.isBoolean(i)){removeLast=i;i=null}if(_.isNumber(i)){if(this.endsWith("{\n"))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":74,lodash:121}],5:[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,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"),flow:require("./generators/flow"),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);var comments=[];_.each(ast.comments,function(comment){if(!comment._displayed)comments.push(comment)});this._printComments(comments);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);if(!self.buffer.get())lines=0}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=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){_.each(self.ast.comments,function(origComment){if(origComment.start===comment.start){origComment._displayed=true;return false}});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":72,"../util":74,"./buffer":4,"./generators/base":6,"./generators/classes":7,"./generators/comprehensions":8,"./generators/expressions":9,"./generators/flow":10,"./generators/jsx":11,"./generators/methods":12,"./generators/modules":13,"./generators/playground":14,"./generators/statements":15,"./generators/template-literals":16,"./generators/types":17,"./node":18,"./position":21,"./source-map":22,"./whitespace":23,lodash:121}],6:[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()}}},{}],7:[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)}},{}],8:[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?")":"]")}},{}],9:[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.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)};var SCIENTIFIC_NOTATION=/e/i;exports.MemberExpression=function(node,print){var obj=node.object;print(obj);if(node.computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(obj)&&util.isInteger(obj.value)&&!SCIENTIFIC_NOTATION.test(obj.value.toString())){this.push(".")}this.push(".");print(node.property)}}},{"../../types":72,"../../util":74}],10:[function(require,module,exports){exports.ClassProperty=function(){throw new Error("not implemented")}},{}],11:[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":72,lodash:121}],12:[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":72}],13:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=function(node,print){if(node.id&&node.id.name==="default"){print(node.name)}else{return exports.ExportSpecifier.apply(this,arguments)}};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(", ")}var isDefault=spec.id&&spec.id.name==="default";if(!isDefault&&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":72,lodash:121}],14:[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:121}],15:[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.PrivateDeclaration=function(node,print){this.push("private ");print.join(node.declarations,{separator:", "});this.semicolon()};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.push(" = ");print(node.init)}else{print(node.id)}}},{"../../types":72}],16:[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:121}],17:[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(/[\u000A\u000D\u2028\u2029]/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:121}],18:[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":72,"./parentheses":19,"./whitespace":20,lodash:121}],19:[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.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":72,lodash:121}],20:[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:{AssignmentExpression:function(node){if(t.isFunction(node.right)){return 1}}},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":72,lodash:121}],21:[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:121}],22:[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":72,"source-map":163}],23:[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}});if(endToken.type.type==="eof"){return 1}else{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:121}],24:[function(require,module,exports){var t=require("./types");var _=require("lodash");var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS);var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;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("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[def("Identifier")]);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()},{"./types":72,"ast-types":88,estraverse:115,lodash:121}],25:[function(require,module,exports){module.exports=DefaultFormatter;var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");function DefaultFormatter(file){this.file=file;this.localExports=this.getLocalExports();this.remapAssignments()}DefaultFormatter.prototype.getLocalExports=function(){var localExports={};traverse(this.file.ast,{enter:function(node){var declar=node&&node.declaration;if(t.isExportDeclaration(node)&&declar&&t.isStatement(declar)){_.extend(localExports,t.getIds(declar,true))}}});return localExports};DefaultFormatter.prototype.remapExportAssignment=function(node){return t.assignmentExpression("=",node.left,t.assignmentExpression(node.operator,t.memberExpression(t.identifier("exports"),node.left),node.right))};DefaultFormatter.prototype.remapAssignments=function(){var localExports=this.localExports;var self=this;var isLocalReference=function(node,scope){var left=node.left;var name=left.name;return t.isIdentifier(left)&&localExports[name]&&localExports[name]===scope.get(name,true)};traverse(this.file.ast,{enter:function(node,parent,scope){if(t.isExportDeclaration(node))return false;if(t.isAssignmentExpression(node)&&isLocalReference(node,scope)){return self.remapExportAssignment(node)}}})};DefaultFormatter.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};DefaultFormatter.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};DefaultFormatter.prototype._hoistExport=function(declar,assign){if(t.isFunctionDeclaration(declar)){assign._blockHoist=true}return assign};DefaultFormatter.prototype._exportSpecifier=function(getRef,specifier,node,nodes){var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){if(t.isExportBatchSpecifier(specifier)){nodes.push(this._exportsWildcard(getRef()))}else{nodes.push(this._exportsAssign(t.getSpecifierName(specifier),t.memberExpression(getRef(),specifier.id)))}}else{nodes.push(this._exportsAssign(t.getSpecifierName(specifier),specifier.id))}};DefaultFormatter.prototype._exportsWildcard=function(objectIdentifier){return util.template("exports-wildcard",{OBJECT:objectIdentifier},true)};DefaultFormatter.prototype._exportsAssign=function(id,init){return util.template("exports-assign",{VALUE:init,KEY:id},true)};DefaultFormatter.prototype.exportDeclaration=function(node,nodes){var declar=node.declaration;if(node.default){nodes.push(this._exportsAssign(t.identifier("default"),this._pushStatement(declar,nodes)))}else{var assign;if(t.isVariableDeclaration(declar)){for(var i in declar.declarations){var decl=declar.declarations[i];decl.init=this._exportsAssign(decl.id,decl.init).expression;var newDeclar=t.variableDeclaration(declar.kind,[decl]);if(i==="0")t.inherits(newDeclar,declar);nodes.push(newDeclar)}}else{assign=this._exportsAssign(declar.id,declar.id);nodes.push(t.toStatement(declar));nodes.push(assign);this._hoistExport(declar,assign)}}}},{"../../traverse":68,"../../types":72,"../../util":74,lodash:121}],26:[function(require,module,exports){module.exports=AMDFormatter;var DefaultFormatter=require("./_default");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(file){this.file=file;this.ids={}}util.inherits(AMDFormatter,DefaultFormatter);AMDFormatter.prototype.buildDependencyLiterals=function(){var names=[];for(var name in this.ids){names.push(t.literal(name))}return names};AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")].concat(this.buildDependencyLiterals());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 DefaultFormatter.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.importDeclaration=function(node){this._push(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var ref=this._push(node);if(t.isImportBatchSpecifier(specifier)){}else if(t.isSpecifierDefault(specifier)){ref=t.callExpression(this.file.addDeclaration("interop-require"),[ref])}else{ref=t.memberExpression(ref,specifier.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":72,"../../util":74,"./_default":25,lodash:121}],27:[function(require,module,exports){module.exports=CommonJSFormatter;var DefaultFormatter=require("./_default");var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");function CommonJSFormatter(file){DefaultFormatter.apply(this,arguments);var hasNonDefaultExports=false;traverse(file.ast,{enter:function(node){if(t.isExportDeclaration(node)&&!node.default)hasNonDefaultExports=true}});this.hasNonDefaultExports=hasNonDefaultExports}util.inherits(CommonJSFormatter,DefaultFormatter);CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(t.isSpecifierDefault(specifier)){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addDeclaration("interop-require"),[util.template("require",{MODULE_NAME:node.source})]))]))}else{var templateName="require-assign";if(specifier.type!=="ImportBatchSpecifier")templateName+="-key";nodes.push(util.template(templateName,{VARIABLE_NAME:variableName,MODULE_NAME:node.source,KEY:specifier.id}))}};CommonJSFormatter.prototype.importDeclaration=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source},true))};CommonJSFormatter.prototype.exportDeclaration=function(node,nodes){if(node.default){var declar=node.declaration;var templateName="exports-default-module";if(this.hasNonDefaultExports)templateName="exports-default-module-override";var assign=util.template(templateName,{VALUE:this._pushStatement(declar,nodes)},true);nodes.push(this._hoistExport(declar,assign))}else{DefaultFormatter.prototype.exportDeclaration.apply(this,arguments)}};CommonJSFormatter.prototype.exportSpecifier=function(specifier,node,nodes){this._exportSpecifier(function(){return t.callExpression(t.identifier("require"),[node.source])},specifier,node,nodes)}},{"../../traverse":68,"../../types":72,"../../util":74,"./_default":25}],28:[function(require,module,exports){module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.exportDeclaration=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.importDeclaration=IgnoreFormatter.prototype.importSpecifier=IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":72}],29:[function(require,module,exports){module.exports=SystemFormatter;var DefaultFormatter=require("./_default");var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function SystemFormatter(file){AMDFormatter.apply(this,arguments);this.moduleNameLiteral=t.literal(this.getModuleName());this.exportIdentifier=file.generateUidIdentifier("export")}util.inherits(SystemFormatter,AMDFormatter);SystemFormatter.prototype.getModuleName=DefaultFormatter.prototype.getModuleName;SystemFormatter.prototype._exportsWildcard=function(objectIdentifier){var leftIdentifier=t.identifier("i");var valIdentifier=t.memberExpression(objectIdentifier,leftIdentifier,true);var left=t.variableDeclaration("var",[t.variableDeclarator(leftIdentifier)]);var right=objectIdentifier;var block=t.blockStatement([this.buildExportCall(leftIdentifier,valIdentifier)]);return t.forInStatement(left,right,block)};SystemFormatter.prototype._exportsAssign=function(id,init){return this.buildExportCall(t.literal(id.name),init,true)};SystemFormatter.prototype.remapExportAssignment=function(node){return this.buildExportCall(t.literal(node.left.name),node)};SystemFormatter.prototype.buildExportCall=function(id,init,isStatement){var call=t.callExpression(this.exportIdentifier,[id,init]);if(isStatement){return t.expressionStatement(call)}else{return call}};SystemFormatter.prototype.buildRunnerSetters=function(){return t.arrayExpression(_.map(this.ids,function(uid){var moduleIdentifier=t.identifier("m");return t.functionExpression(null,[moduleIdentifier],t.blockStatement([t.assignmentExpression("=",uid,moduleIdentifier)]))}))};SystemFormatter.prototype.transform=function(ast){var program=ast.program;var runner=util.template("system",{MODULE_NAME:this.moduleNameLiteral,MODULE_DEPENDENCIES:t.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(),EXECUTE:t.functionExpression(null,[],t.blockStatement(program.body))},true);if(!_.isEmpty(this.ids)){var handlerBody=runner.expression.arguments[2].body.body;handlerBody.unshift(t.variableDeclaration("var",_.map(this.ids,function(uid){return t.variableDeclarator(uid)})))}program.body=[runner]}},{"../../types":72,"../../util":74,"./_default":25,"./amd":26,lodash:121}],30:[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=[];for(var name in this.ids){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":72,"../../util":74,"./amd":26,lodash:121}],31:[function(require,module,exports){module.exports=transform;var Transformer=require("./transformer");var File=require("../file");var util=require("../util");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform.fromAst=function(ast,code,opts){ast=util.normaliseAst(ast);var file=new File(opts);file.addCode(code);file.transform(ast);return file.generate()};transform._ensureTransformerNames=function(type,keys){for(var i in keys){var key=keys[i];if(!_.has(transform.transformers,key)){throw new ReferenceError("unknown transformer "+key+" specified in "+type)}}};transform.transformers={};transform.moduleFormatters={common:require("./modules/common"),system:require("./modules/system"),ignore:require("./modules/ignore"),amd:require("./modules/amd"),umd:require("./modules/umd")};_.each({specBlockHoistFunctions:require("./transformers/spec-block-hoist-functions"),specNoForInOfAssignment:require("./transformers/spec-no-for-in-of-assignment"),specNoDuplicateProperties:require("./transformers/spec-no-duplicate-properties"),methodBinding:require("./transformers/playground-method-binding"),memoizationOperator:require("./transformers/playground-memoization-operator"),objectGetterMemoization:require("./transformers/playground-object-getter-memoization"),react:require("./transformers/react"),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"),destructuring:require("./transformers/es6-destructuring"),defaultParameters:require("./transformers/es6-default-parameters"),forOf:require("./transformers/es6-for-of"),unicodeRegex:require("./transformers/es6-unicode-regex"),abstractReferences:require("./transformers/es7-abstract-references"),constants:require("./transformers/es6-constants"),letScoping:require("./transformers/es6-let-scoping"),_blockHoist:require("./transformers/_block-hoist"),generators:require("./transformers/es6-generators"),restParameters:require("./transformers/es6-rest-parameters"),_declarations:require("./transformers/_declarations"),_aliasFunctions:require("./transformers/_alias-functions"),useStrict:require("./transformers/use-strict"),_moduleFormatter:require("./transformers/_module-formatter"),specPropertyLiterals:require("./transformers/spec-property-literals"),specMemberExpressionLiterals:require("./transformers/spec-member-expression-literals")},function(transformer,key){transform.transformers[key]=new Transformer(key,transformer)})},{"../file":3,"../util":74,"./modules/amd":26,"./modules/common":27,"./modules/ignore":28,"./modules/system":29,"./modules/umd":30,"./transformer":32,"./transformers/_alias-functions":33,"./transformers/_block-hoist":34,"./transformers/_declarations":35,"./transformers/_module-formatter":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":45,"./transformers/es6-let-scoping":46,"./transformers/es6-modules":47,"./transformers/es6-property-name-shorthand":48,"./transformers/es6-rest-parameters":49,"./transformers/es6-spread":50,"./transformers/es6-template-literals":51,"./transformers/es6-unicode-regex":52,"./transformers/es7-abstract-references":53,"./transformers/es7-array-comprehension":54,"./transformers/es7-exponentiation-operator":55,"./transformers/es7-generator-comprehension":56,"./transformers/es7-object-spread":57,"./transformers/playground-memoization-operator":58,"./transformers/playground-method-binding":59,"./transformers/playground-object-getter-memoization":60,"./transformers/react":61,"./transformers/spec-block-hoist-functions":62,"./transformers/spec-member-expression-literals":63,"./transformers/spec-no-duplicate-properties":64,"./transformers/spec-no-for-in-of-assignment":65,"./transformers/spec-property-literals":66,"./transformers/use-strict":67,lodash:121}],32:[function(require,module,exports){module.exports=Transformer;
var traverse=require("../traverse");var t=require("../types");var _=require("lodash");function Transformer(key,transformer,opts){this.transformer=Transformer.normalise(transformer);this.opts=opts||{};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;var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){_.each(aliases,function(alias){transformer[alias]=fns})}});return transformer};Transformer.prototype.astRun=function(file,key){var transformer=this.transformer;var ast=file.ast;if(transformer.ast&&transformer.ast[key]){transformer.ast[key](ast,file)}};Transformer.prototype.transform=function(file){if(!this.canRun(file))return;var transformer=this.transformer;var ast=file.ast;this.astRun(file,"enter");var build=function(exit){return function(node,parent,scope){var fns=transformer[node.type];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)});this.astRun(file,"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":68,"../types":72,lodash:121}],33:[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,{enter:function(node){if(!node._aliasFunction){if(t.isFunction(node)){return false}else{return}}traverse(node,{enter: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":68,"../../types":72}],34:[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)}}},{}],35:[function(require,module,exports){var t=require("../../types");exports.BlockStatement=exports.Program=function(node){var kinds={};var kind;for(var i in node._declarations){var declar=node._declarations[i];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]))}}for(kind in kinds){node.body.unshift(t.variableDeclaration(kind,kinds[kind]))}}},{"../../types":72}],36:[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":31}],37:[function(require,module,exports){var util=require("../../util");exports.Property=function(node){if(node.method)node.method=false};exports.ObjectExpression=function(node,parent,file){var mutatorMap={};var hasAny=false;node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){hasAny=true;util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.value);return false}else{return true}});if(!hasAny)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":74}],38:[function(require,module,exports){var t=require("../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction="arrow";node.expression=false;node.type="FunctionExpression";return node}},{"../../types":72}],39:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");exports.ClassDeclaration=function(node,parent,file,scope){var closure=true;if(t.isProgram(parent)||t.isBlockStatement(parent)){closure=false}var newNode=new Class(node,file,scope,closure).run();if(closure){scope.push({kind:"var",key:node.id.key,id:node.id});return t.assignmentExpression("=",node.id,newNode)}else{return newNode}};exports.ClassExpression=function(node,parent,file,scope){return new Class(node,file,scope,true).run()};function Class(node,file,scope,closure){this.closure=closure;this.scope=scope;this.node=node;this.file=file;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||file.generateUidIdentifier("class",scope);this.superName=node.superClass}Class.prototype.run=function(){var superName=this.superName;var className=this.className;var file=this.file;var body=this.body=[];var constructor=t.functionExpression(null,[],t.blockStatement([]));if(this.node.id)constructor.id=className;this.constructor=constructor;body.push(t.variableDeclaration("let",[t.variableDeclarator(className,constructor)]));if(superName&&t.isDynamic(superName)){var superRefName="super";if(className)superRefName=className.name+"Super";var superRef=file.generateUidIdentifier(superRefName,this.scope);body.unshift(t.variableDeclaration("var",[t.variableDeclarator(superRef,superName)]));superName=superRef}this.superName=superName;if(superName){body.push(t.expressionStatement(t.callExpression(file.addDeclaration("inherits"),[className,superName])))}this.buildBody();t.inheritsComments(body[0],this.node);if(this.closure){if(body.length===1){return constructor}else{body.push(t.returnStatement(className));return t.callExpression(t.functionExpression(null,[],t.blockStatement(body)),[])}}else{return body}};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;for(var i in classBody){var node=classBody[i];if(t.isMethodDefinition(node)){self.replaceInstanceSuperReferences(node);if(node.key.name==="constructor"){self.pushConstructor(node)}else{self.pushMethod(node)}}else if(t.isPrivateDeclaration(node)){self.closure=true;body.unshift(node)}}if(!this.hasConstructor&&superName){constructor.body.body.push(util.template("class-super-constructor-call",{SUPER_NAME:superName},true))}var instanceProps;var staticProps;if(this.hasInstanceMutators){var protoId=util.template("prototype-identifier",{CLASS_NAME:className});instanceProps=util.buildDefineProperties(this.instanceMutatorMap,protoId)}if(this.hasStaticMutators){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("prototype-properties"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var kind=node.kind;if(kind===""){var className=this.className;if(!node.static)className=t.memberExpression(className,t.identifier("prototype"));methodName=t.memberExpression(className,methodName,node.computed);var expr=t.expressionStatement(t.assignmentExpression("=",methodName,node.value));t.inheritsComments(expr,node);this.body.push(expr)}else{var mutatorMap=this.instanceMutatorMap;if(node.static){this.hasStaticMutators=true;mutatorMap=this.staticMutatorMap}else{this.hasInstanceMutators=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,{enter: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":68,"../../types":72,"../../util":74}],40:[function(require,module,exports){var util=require("../../util");var t=require("../../types");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;var containerBody=containerCallee.body.body;containerCallee._aliasFunction=true;for(var i in computed){var prop=computed[i];containerBody.unshift(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,true),prop.value)))}return container}},{"../../types":72,"../../util":74}],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 hasConstants=false;var constants={};var check=function(parent,names,scope){for(var name in names){var nameNode=names[name];if(!_.has(constants,name))continue;if(parent&&t.isBlockStatement(parent)&&parent!==constants[name])continue;if(scope){var defined=scope.get(name);if(defined&&defined===nameNode)continue}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(t.isExportDeclaration(child)){child=child.declaration}if(t.isVariableDeclaration(child,{kind:"const"})){for(var i in child.declarations){var declar=child.declarations[i];var ids=getIds(declar);for(var name in ids){var nameNode=ids[name];var names={};names[name]=nameNode;check(parent,names);constants[name]=parent;hasConstants=true}declar._ignoreConstant=true}child._ignoreConstant=true;child.kind="let"}});if(!hasConstants)return;traverse(node,{enter:function(child,parent,scope){if(child._ignoreConstant)return;if(t.isVariableDeclaration(child))return;if(t.isVariableDeclarator(child)||t.isDeclaration(child)||t.isAssignmentExpression(child)){check(parent,getIds(child),scope)}}})}},{"../../traverse":68,"../../types":72,lodash:121}],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 iife=false;var i;var def;for(i in node.defaults){def=node.defaults[i];if(!def)continue;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(ids.indexOf(node.name)>=0){throw file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}if(scope.has(node.name)){iife=true}};check(def,node);traverse(def,{enter:check})});var has=scope.get(param.name);if(has&&node.params.indexOf(has)<0){iife=true}}var body=[];for(i in node.defaults){def=node.defaults[i];if(!def)continue;body.push(util.template("if-undefined-set-to",{VARIABLE:node.params[i],DEFAULT:def},true))}if(iife){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":68,"../../types":72,"../../util":74,lodash:121}],43:[function(require,module,exports){var t=require("../../types");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){for(var i in pattern.properties){var prop=pattern.properties[i];if(t.isSpreadProperty(prop)){var keys=[];for(var i2 in pattern.properties){var prop2=pattern.properties[i2];if(i2>=i)break;if(t.isSpreadProperty(prop2))continue;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-without-properties"),[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;for(var i in pattern.elements){var elem=pattern.elements[i];if(!elem)continue;i=+i;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 i;var declar;var hasPattern=false;for(i in node.declarations){declar=node.declarations[i];if(t.isPattern(declar.id)){hasPattern=true;break}}if(!hasPattern)return;for(i in node.declarations){declar=node.declarations[i];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)){for(i in nodes){node=nodes[i];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":72}],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":72,"../../util":74}],45:[function(require,module,exports){module.exports=require("regenerator").transform},{regenerator:129}],46:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");var isLet=function(node,parent){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;if(!t.isFor(parent)||t.isFor(parent)&&parent.left!==node){_.each(node.declarations,function(declar){declar.init=declar.init||t.identifier("undefined")})}node._let=true;node.kind="var";return true};var isVar=function(node,parent){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node,parent)};var standardiseLets=function(declars){for(var i in declars){delete declars[i]._let}};exports.VariableDeclaration=function(node,parent){isLet(node,parent)};exports.Loop=function(node,parent,file,scope){var init=node.left||node.init;if(isLet(init,node)){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.isLoop(parent)){var letScoping=new LetScoping(false,block,parent,file,scope);letScoping.run()}};function LetScoping(loopParent,block,parent,file,scope){this.loopParent=loopParent;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.checkLoop();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(!this.info.hasDuplicates)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,{enter:replace})};var loopParent=this.loopParent;if(loopParent){traverseReplace(loopParent.right,loopParent);traverseReplace(loopParent.test,loopParent);traverseReplace(loopParent.update,loopParent)}traverse(block,{enter:replace})};LetScoping.prototype.getInfo=function(){var block=this.block;var scope=this.scope;var file=this.file;var opts={outsideKeys:[],declarators:block._letDeclars||[],duplicates:{},hasDuplicates:false,keys:[]};var duplicates=function(id,key){var has=scope.parentGet(key);if(has&&has!==id){opts.duplicates[key]=id.name=file.generateUid(key,scope);opts.hasDuplicates=true}};var i;var declar;for(i in opts.declarators){declar=opts.declarators[i];opts.declarators.push(declar);var keys=t.getIds(declar,true);_.each(keys,duplicates);keys=Object.keys(keys);opts.outsideKeys=opts.outsideKeys.concat(keys);opts.keys=opts.keys.concat(keys)}for(i in block.body){declar=block.body[i];if(!isLet(declar,block))continue;_.each(t.getIds(declar,true),function(id,key){duplicates(id,key);opts.keys.push(key)})}return opts};LetScoping.prototype.checkLoop=function(){var has={hasContinue:false,hasReturn:false,hasBreak:false};traverse(this.block,{enter:function(node,parent){var replace;if(t.isFunction(node)||t.isLoop(node)){return false}if(node&&!node.label){if(t.isBreakStatement(node)){if(t.isSwitchCase(parent))return;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,{enter:function(node,parent){if(t.isForStatement(node)){if(isVar(node.init,node)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left,node)){node.left=node.left.declarations[0].id}}else if(isVar(node,parent)){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,{enter:function(node,parent,scope){if(t.isFunction(node)){traverse(node,{enter: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.isLoop(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=[];for(var i in node.declarations){var declar=node.declarations[i];if(!declar.init)continue;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 loopParent=this.loopParent;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=loopParent.label=loopParent.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":68,"../../types":72,"../../util":74,lodash:121}],47:[function(require,module,exports){var t=require("../../types");var inheritsComments=function(node,nodes){if(nodes.length){t.inheritsComments(nodes[0],node)}};exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){if(!file.moduleFormatter.importSpecifier)return;for(var i in node.specifiers){file.moduleFormatter.importSpecifier(node.specifiers[i],node,nodes,parent)}}else{if(!file.moduleFormatter.importDeclaration)return;file.moduleFormatter.importDeclaration(node,nodes,parent)}inheritsComments(node,nodes);return nodes};exports.ExportDeclaration=function(node,parent,file){var nodes=[];if(node.declaration){if(t.isVariableDeclaration(node.declaration)){var declar=node.declaration.declarations[0];declar.init=declar.init||t.identifier("undefined")}if(!file.moduleFormatter.exportDeclaration)return;file.moduleFormatter.exportDeclaration(node,nodes,parent)}else{if(!file.moduleFormatter.exportSpecifier)return;for(var i in node.specifiers){file.moduleFormatter.exportSpecifier(node.specifiers[i],node,nodes,parent)}}inheritsComments(node,nodes);return nodes}},{"../../types":72}],48:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.Property=function(node){if(!node.shorthand)return;node.shorthand=false;node.key=t.removeComments(_.clone(node.key))}},{"../../types":72,lodash:121}],49:[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":72}],50:[function(require,module,exports){var t=require("../../types");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){for(var i in nodes){if(t.isSpreadElement(nodes[i])){return true}}return false};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};for(var i in props){var prop=props[i];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,scope){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;var temp;if(t.isMemberExpression(callee)){contextLiteral=callee.object;if(t.isDynamic(contextLiteral)){temp=contextLiteral=scope.generateTemp(file);callee.object=t.assignmentExpression("=",temp,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":72}],51:[function(require,module,exports){var t=require("../../types");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=[];for(var i in quasi.quasis){var elem=quasi.quasis[i];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=[];var i;for(i in node.quasis){var elem=node.quasis[i];nodes.push(t.literal(elem.value.cooked));var expr=node.expressions.shift();if(expr)nodes.push(expr)}if(nodes.length>1){var last=nodes[nodes.length-1];if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());for(i in nodes){root=buildBinaryExpression(root,nodes[i])}return root}else{return nodes[0]}}},{"../../types":72}],52:[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(regex.flags.indexOf("u")<0)return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:121,"regexpu/rewrite-pattern":162}],53:[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)){temp=value=scope.generateTemp(file)}}if(node.operator!=="="){value=t.binaryExpression(node.operator[0],util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object}),value)}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)){temp=scope.generateTemp(file)}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})};exports.PrivateDeclaration=function(node){return t.variableDeclaration("const",node.declarations.map(function(id){return t.variableDeclarator(id,t.newExpression(t.identifier("WeakMap"),[]))}))}},{"../../types":72,"../../util":74}],54:[function(require,module,exports){var util=require("../../util");var t=require("../../types");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});var aliasPossibles=[result.callee.object,result];for(var i in aliasPossibles){var call=aliasPossibles[i];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.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":72,"../../util":74}],55:[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":72}],56:[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);container._aliasFunction=true;body.push(arrayComprehension._build(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])}},{"../../types":72,"./es7-array-comprehension":54}],57:[function(require,module,exports){var t=require("../../types");exports.ObjectExpression=function(node){var hasSpread=false;var i;var prop;for(i in node.properties){prop=node.properties[i];if(t.isSpreadProperty(prop)){hasSpread=true;break}}if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};for(i in node.properties){prop=node.properties[i];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":72}],58:[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":72}],59:[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)){temp=object=scope.generateTemp(file)}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 temp=scope.generateTemp(file,"args");return t.sequenceExpression([t.assignmentExpression("=",temp,t.arrayExpression(node.arguments)),buildCall(node.arguments.map(function(node,i){return t.memberExpression(temp,t.literal(i),true)}))])}else{return buildCall(node.arguments)}}},{"../../types":72,lodash:121}],60:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");exports.Property=exports.MethodDefinition=function(node,parent,file,scope){if(node.kind!=="memo")return;node.kind="get";var value=node.value;t.ensureBlock(value);var body=value.body.body;var key=node.key;if(t.isIdentifier(key)&&!node.computed){key="_"+key.name}else{key=file.generateUid("memo",scope)}var memoId=t.memberExpression(t.thisExpression(),t.identifier(key));var doneId=t.memberExpression(t.thisExpression(),t.identifier(key+"Done"));traverse(value,{enter:function(node){if(t.isFunction(node))return;if(t.isReturnStatement(node)&&node.argument){node.argument=t.assignmentExpression("=",memoId,node.argument)}}});body.unshift(t.expressionStatement(t.assignmentExpression("=",doneId,t.literal(true))));body.unshift(t.ifStatement(doneId,t.returnStatement(memoId)))}},{"../../traverse":68,"../../types":72}],61:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");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])||tagName.indexOf("-")>=0)){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;var i;for(i in node.children){var child=node.children[i];if(t.isLiteral(child)){var lines=child.value.split(/\r\n|\n|\r/);for(i in lines){var line=lines[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))}}continue}else if(t.isXJSEmptyExpression(child)){continue}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;for(var i in props){prop=props[i];if(t.isIdentifier(prop.key,{name:"displayName"})){safe=false;break}}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":72,esutils:119}],62:[function(require,module,exports){var t=require("../../types");exports.BlockStatement=function(node,parent){if(t.isFunction(parent))return;node.body=node.body.map(function(node){if(t.isFunction(node)){node.type="FunctionExpression";var declar=t.variableDeclaration("let",[t.variableDeclarator(node.id,node)]);declar._blockHoist=true;return declar}else{return node}})}},{"../../types":72}],63:[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":72,esutils:119}],64:[function(require,module,exports){var t=require("../../types");exports.ObjectExpression=function(node,parent,file){var keys=[];for(var i in node.properties){var prop=node.properties[i];if(prop.computed||prop.kind!=="init")continue;var key=prop.key;if(t.isIdentifier(key)){key=key.name}else if(t.isLiteral(key)){key=key.value}else{continue}if(keys.indexOf(key)>=0){throw file.errorWithNode(prop.key,"Duplicate property key")}else{keys.push(key)}}}},{"../../types":72}],65:[function(require,module,exports){var t=require("../../types");exports.ForInStatement=exports.ForOfStatement=function(node,parent,file){var left=node.left;if(t.isVariableDeclaration(left)){var declar=left.declarations[0];if(declar.init)throw file.errorWithNode(declar,"No assignments allowed in for-in/of head")}}},{"../../types":72}],66:[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":72,esutils:119}],67:[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":72}],68:[function(require,module,exports){module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function traverse(parent,opts,scope){if(!parent)return;if(_.isArray(parent)){_.each(parent,function(node){traverse(node,opts,scope)});return}var keys=t.VISITOR_KEYS[parent.type];if(!keys)return;opts=opts||{};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(opts.blacklist&&opts.blacklist.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 ourScope=scope;if(t.isScope(node))ourScope=new Scope(node,scope);if(opts.enter){var result=opts.enter(node,parent,ourScope);maybeReplace(result);if(result===false)return}traverse(node,opts,ourScope);if(opts.exit){maybeReplace(opts.exit(node,parent,ourScope))}};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._declarations;delete node.extendedRange;delete node._scopeInfo;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,{enter: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,{blacklist:blacklistTypes,enter:function(node){if(node.type===type){has=true;return false}}});return has}},{"../types":72,"./scope":69,lodash:121}],69:[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;var info=this.getInfo();this.references=info.references;this.declarations=info.declarations}var vars=require("jshint/src/vars");Scope.defaultDeclarations=_.flatten([vars.newEcmaIdentifiers,vars.node,vars.ecmaIdentifiers,vars.reservedVars].map(_.keys));Scope.add=function(node,references){if(!node)return;_.defaults(references,t.getIds(node,true))};Scope.prototype.generateTemp=function(file,name){var id=file.generateUidIdentifier(name||"temp",this);this.push({key:id.name,id:id});return id};Scope.prototype.getInfo=function(){var block=this.block;if(block._scopeInfo)return block._scopeInfo;var info=block._scopeInfo={};var references=info.references={};var declarations=info.declarations={};var add=function(node,reference){Scope.add(node,references);if(!reference)Scope.add(node,declarations)};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,{enter: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(block.id&&node===block.id)return;if(t.isIdentifier(node)&&t.isReferenced(node,parent)&&!scope.has(node.name)){add(node,true)}if(t.isDeclaration(node)&&!t.isLet(node)){add(node)}}},this)}if(t.isFunction(block)){add(block.rest);_.each(block.params,function(param){add(param)})}return info};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,decl){return id&&(this.getOwn(id,decl)||this.parentGet(id,decl))};Scope.prototype.getOwn=function(id,decl){var refs=this.references;if(decl)refs=this.declarations;return _.has(refs,id)&&refs[id]};Scope.prototype.parentGet=function(id,decl){return this.parent&&this.parent.get(id,decl)};Scope.prototype.has=function(id,decl){return id&&(this.hasOwn(id,decl)||this.parentHas(id,decl))||_.contains(Scope.defaultDeclarations,id)};Scope.prototype.hasOwn=function(id,decl){return!!this.getOwn(id,decl)};Scope.prototype.parentHas=function(id,decl){return this.parent&&this.parent.has(id,decl)}},{"../types":72,"./index":68,"jshint/src/vars":120,lodash:121}],70:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function"],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","Loop"],ForInStatement:["Statement","For","Scope","Loop"],ForStatement:["Statement","For","Scope","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable"]}},{}],71:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrowFunctionExpression:["params","body"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],WithStatement:["object","body"],YieldExpression:["argument","delegate"]}},{}],72:[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");t.FLIPPED_ALIAS_KEYS={};_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=t.FLIPPED_ALIAS_KEYS[alias]=t.FLIPPED_ALIAS_KEYS[alias]||[];types.push(type)})});_.each(t.FLIPPED_ALIAS_KEYS,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;var is=t["is"+type]=function(node,opts){return node&&types.indexOf(node.type)>=0&&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.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&&!parent.computed)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:"name",ExportSpecifier:"name",VariableDeclarator:"id",FunctionDeclaration:"id",ClassDeclaration:"id",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.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};t.isSpecifierDefault=function(specifier){return t.isIdentifier(specifier.id)&&specifier.id.name==="default"}},{"./alias-keys":70,"./builder-keys":71,"./visitor-keys":73,esutils:119,lodash:121}],73:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ClassProperty:["key"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateDeclaration:["declarations"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],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"]}
},{}],74:[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);map.enumerable=t.literal(true);_.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,{enter:function(node){if(t.isIdentifier(node)&&_.has(nodes,node.name)){return nodes[node.name]}}})}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(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.normaliseAst=function(ast,comments,tokens){if(ast&&ast.type==="Program"){return t.file(ast,comments||[],tokens||[])}else{throw new Error("Not a valid ast?")}};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowImportExportEverywhere:true,allowReturnOutsideFunction: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=exports.normaliseAst(ast,comments,tokens);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":173,"./patch":24,"./traverse":68,"./types":72,"acorn-6to5":1,buffer:91,estraverse:115,fs:89,lodash:121,path:98,util:114}],75:[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("Printable").field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("Node").bases("Printable").field("type",isString);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")]).field("comments",or([or(def("Block"),def("Line"))],null),defaults["null"],true);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));def("Block").bases("Printable").build("loc","value").field("value",isString);def("Line").bases("Printable").build("loc","value").field("value",isString)},{"../lib/shared":86,"../lib/types":87}],76:[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":87,"./core":75}],77:[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("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("PropertyPattern").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).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"),def("Expression"))).field("value",def("Function")).field("computed",isBoolean,defaults["false"]);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("key").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);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"]).field("implements",[def("ClassImplements")],defaults.emptyArray);def("ClassImplements").bases("Node").build("id").field("id",def("Identifier")).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":86,"../lib/types":87,"./core":75}],78:[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":86,"../lib/types":87,"./core":75}],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;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("Type").bases("Node");def("AnyTypeAnnotation").bases("Type");def("VoidTypeAnnotation").bases("Type");def("NumberTypeAnnotation").bases("Type");def("StringTypeAnnotation").bases("Type");def("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",isString).field("raw",isString);def("BooleanTypeAnnotation").bases("Type");def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",def("Type"));def("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",def("Type"));def("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[def("FunctionTypeParam")]).field("returnType",def("Type")).field("rest",or(def("FunctionTypeParam"),null)).field("typeParameters",or(def("TypeParameterDeclaration"),null));def("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",def("Identifier")).field("typeAnnotation",def("Type")).field("optional",isBoolean);def("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[def("ObjectTypeProperty")]).field("indexers",[def("ObjectTypeIndexer")],defaults.emptyArray).field("callProperties",[def("ObjectTypeCallProperty")],defaults.emptyArray);def("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",or(def("Literal"),def("Identifier"))).field("value",def("Type")).field("optional",isBoolean);def("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",def("Identifier")).field("key",def("Type")).field("value",def("Type"));def("ObjectTypeCallProperty").bases("Node").build("value").field("value",def("FunctionTypeAnnotation")).field("static",isBoolean,false);def("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("id",def("Identifier"));def("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("MemberTypeAnnotation").bases("Type").build("object","property").field("object",def("Identifier")).field("property",or(def("MemberTypeAnnotation"),def("GenericTypeAnnotation")));def("UnionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",def("Type"));def("Identifier").field("typeAnnotation",or(def("TypeAnnotation"),null),defaults["null"]);def("TypeParameterDeclaration").bases("Node").build("params").field("params",[def("Identifier")]);def("TypeParameterInstantiation").bases("Node").build("params").field("params",[def("Type")]);def("Function").field("returnType",or(def("TypeAnnotation"),null),defaults["null"]).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]);def("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",def("TypeAnnotation")).field("static",isBoolean,false);def("ClassImplements").field("typeParameters",or(def("TypeParameterInstantiation"),null),defaults["null"]);def("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]).field("body",def("ObjectTypeAnnotation")).field("extends",[def("InterfaceExtends")]);def("InterfaceExtends").bases("Node").build("id").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null)).field("right",def("Type"));def("TupleTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("DeclareVariable").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareFunction").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareClass").bases("InterfaceDeclaration").build("id");def("DeclareModule").bases("Statement").build("id","body").field("id",or(def("Identifier"),def("Literal"))).field("body",def("BlockStatement"))},{"../lib/shared":86,"../lib/types":87,"./core":75}],80:[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":86,"../lib/types":87,"./core":75}],81:[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":88,assert:90}],82:[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":84,"./scope":85,"./types":87,assert:90,util:114}],83:[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);this._visiting=false;this._changeReported=false}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;var recursiveVisitWarning=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");PVp.visit=function(path){assert.ok(!this._visiting,recursiveVisitWarning);this._visiting=true;this._changeReported=false;this.reset.apply(this,arguments);try{return this.visitWithoutReset(path)}finally{this._visiting=false}};PVp.reset=function(path){};PVp.visitWithoutReset=function(path){if(this instanceof this.Context){return this.visitor.visitWithoutReset(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.visitWithoutReset,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.visitWithoutReset(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};PVp.reportChanged=function(){this._changeReported=true};PVp.wasChangeReported=function(){return this._changeReported};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))};sharedContextProtoMethods.visit=function visit(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;PathVisitor.fromMethodsObject(newVisitor||this.visitor).visitWithoutReset(path)};sharedContextProtoMethods.reportChanged=function reportChanged(){this.visitor.reportChanged()};module.exports=PathVisitor},{"./node-path":82,"./types":87,assert:90}],84:[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":87,assert:90}],85:[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":82,"./types":87,assert:90}],86:[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":87}],87:[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:90}],88:[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":75,"./def/e4x":76,"./def/es6":77,"./def/es7":78,"./def/fb-harmony":79,"./def/mozilla":80,"./lib/equiv":81,"./lib/node-path":82,"./lib/path-visitor":83,"./lib/types":87}],89:[function(require,module,exports){},{}],90:[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/":114}],91:[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,2);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,unitSize){if(unitSize)length-=length%unitSize;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":92,ieee754:93,"is-array":94}],92:[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)},{}],93:[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}},{}],94:[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)}},{}],95:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],96:[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}}},{}],97:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],98:[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:99}],99:[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")}},{}],100:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":101}],101:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":103,"./_stream_writable":105,_process:99,"core-util-is":106,inherits:96}],102:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":104,"core-util-is":106,inherits:96}],103:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause")};function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:99,buffer:91,"core-util-is":106,events:95,inherits:96,isarray:97,stream:111,"string_decoder/":112}],104:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":101,"core-util-is":106,inherits:96}],105:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;
for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":101,_process:99,buffer:91,"core-util-is":106,inherits:96,stream:111}],106:[function(require,module,exports){(function(Buffer){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;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:91}],107:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":102}],108:[function(require,module,exports){var Stream=require("stream");exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":101,"./lib/_stream_passthrough.js":102,"./lib/_stream_readable.js":103,"./lib/_stream_transform.js":104,"./lib/_stream_writable.js":105,stream:111}],109:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":104}],110:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":105}],111:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:95,inherits:96,"readable-stream/duplex.js":100,"readable-stream/passthrough.js":107,"readable-stream/readable.js":108,"readable-stream/transform.js":109,"readable-stream/writable.js":110}],112:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:91}],113:[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"}},{}],114:[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":113,_process:99,inherits:96}],115:[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})},{}],116:[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}})()},{}],117:[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}})()},{}],118:[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":117}],119:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":116,"./code":117,"./keyword":118}],120:[function(require,module,exports){"use strict";exports.reservedVars={arguments:false,NaN:false};exports.ecmaIdentifiers={Array:false,Boolean:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Function:false,hasOwnProperty:false,isFinite:false,isNaN:false,JSON:false,Map:false,Math:false,Number:false,Object:false,Proxy:false,Promise:false,parseInt:false,parseFloat:false,RangeError:false,ReferenceError:false,RegExp:false,Set:false,String:false,SyntaxError:false,TypeError:false,URIError:false,WeakMap:false,WeakSet:false};exports.newEcmaIdentifiers={Set:false,Map:false,WeakMap:false,WeakSet:false,Proxy:false,Promise:false,Reflect:false,Symbol:false,System:false};exports.browser={Audio:false,Blob:false,addEventListener:false,applicationCache:false,atob:false,blur:false,btoa:false,cancelAnimationFrame:false,CanvasGradient:false,CanvasPattern:false,CanvasRenderingContext2D:false,CSS:false,clearInterval:false,clearTimeout:false,close:false,closed:false,CustomEvent:false,DOMParser:false,defaultStatus:false,Document:false,document:false,Element:false,ElementTimeControl:false,Event:false,event:false,FileReader:false,FormData:false,focus:false,frames:false,getComputedStyle:false,HTMLElement:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,history:false,Image:false,Intl:false,length:false,localStorage:false,location:false,matchMedia:false,MessageChannel:false,MessageEvent:false,MessagePort:false,MouseEvent:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,Node:false,NodeFilter:false,NodeList:false,navigator:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,Option:false,parent:false,print:false,requestAnimationFrame:false,removeEventListener:false,resizeBy:false,resizeTo:false,screen:false,scroll:false,scrollBy:false,scrollTo:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,status:false,SVGAElement:false,SVGAltGlyphDefElement:false,SVGAltGlyphElement:false,SVGAltGlyphItemElement:false,SVGAngle:false,SVGAnimateColorElement:false,SVGAnimateElement:false,SVGAnimateMotionElement:false,SVGAnimateTransformElement:false,SVGAnimatedAngle:false,SVGAnimatedBoolean:false,SVGAnimatedEnumeration:false,SVGAnimatedInteger:false,SVGAnimatedLength:false,SVGAnimatedLengthList:false,SVGAnimatedNumber:false,SVGAnimatedNumberList:false,SVGAnimatedPathData:false,SVGAnimatedPoints:false,SVGAnimatedPreserveAspectRatio:false,SVGAnimatedRect:false,SVGAnimatedString:false,SVGAnimatedTransformList:false,SVGAnimationElement:false,SVGCSSRule:false,SVGCircleElement:false,SVGClipPathElement:false,SVGColor:false,SVGColorProfileElement:false,SVGColorProfileRule:false,SVGComponentTransferFunctionElement:false,SVGCursorElement:false,SVGDefsElement:false,SVGDescElement:false,SVGDocument:false,SVGElement:false,SVGElementInstance:false,SVGElementInstanceList:false,SVGEllipseElement:false,SVGExternalResourcesRequired:false,SVGFEBlendElement:false,SVGFEColorMatrixElement:false,SVGFEComponentTransferElement:false,SVGFECompositeElement:false,SVGFEConvolveMatrixElement:false,SVGFEDiffuseLightingElement:false,SVGFEDisplacementMapElement:false,SVGFEDistantLightElement:false,SVGFEFloodElement:false,SVGFEFuncAElement:false,SVGFEFuncBElement:false,SVGFEFuncGElement:false,SVGFEFuncRElement:false,SVGFEGaussianBlurElement:false,SVGFEImageElement:false,SVGFEMergeElement:false,SVGFEMergeNodeElement:false,SVGFEMorphologyElement:false,SVGFEOffsetElement:false,SVGFEPointLightElement:false,SVGFESpecularLightingElement:false,SVGFESpotLightElement:false,SVGFETileElement:false,SVGFETurbulenceElement:false,SVGFilterElement:false,SVGFilterPrimitiveStandardAttributes:false,SVGFitToViewBox:false,SVGFontElement:false,SVGFontFaceElement:false,SVGFontFaceFormatElement:false,SVGFontFaceNameElement:false,SVGFontFaceSrcElement:false,SVGFontFaceUriElement:false,SVGForeignObjectElement:false,SVGGElement:false,SVGGlyphElement:false,SVGGlyphRefElement:false,SVGGradientElement:false,SVGHKernElement:false,SVGICCColor:false,SVGImageElement:false,SVGLangSpace:false,SVGLength:false,SVGLengthList:false,SVGLineElement:false,SVGLinearGradientElement:false,SVGLocatable:false,SVGMPathElement:false,SVGMarkerElement:false,SVGMaskElement:false,SVGMatrix:false,SVGMetadataElement:false,SVGMissingGlyphElement:false,SVGNumber:false,SVGNumberList:false,SVGPaint:false,SVGPathElement:false,SVGPathSeg:false,SVGPathSegArcAbs:false,SVGPathSegArcRel:false,SVGPathSegClosePath:false,SVGPathSegCurvetoCubicAbs:false,SVGPathSegCurvetoCubicRel:false,SVGPathSegCurvetoCubicSmoothAbs:false,SVGPathSegCurvetoCubicSmoothRel:false,SVGPathSegCurvetoQuadraticAbs:false,SVGPathSegCurvetoQuadraticRel:false,SVGPathSegCurvetoQuadraticSmoothAbs:false,SVGPathSegCurvetoQuadraticSmoothRel:false,SVGPathSegLinetoAbs:false,SVGPathSegLinetoHorizontalAbs:false,SVGPathSegLinetoHorizontalRel:false,SVGPathSegLinetoRel:false,SVGPathSegLinetoVerticalAbs:false,SVGPathSegLinetoVerticalRel:false,SVGPathSegList:false,SVGPathSegMovetoAbs:false,SVGPathSegMovetoRel:false,SVGPatternElement:false,SVGPoint:false,SVGPointList:false,SVGPolygonElement:false,SVGPolylineElement:false,SVGPreserveAspectRatio:false,SVGRadialGradientElement:false,SVGRect:false,SVGRectElement:false,SVGRenderingIntent:false,SVGSVGElement:false,SVGScriptElement:false,SVGSetElement:false,SVGStopElement:false,SVGStringList:false,SVGStylable:false,SVGStyleElement:false,SVGSwitchElement:false,SVGSymbolElement:false,SVGTRefElement:false,SVGTSpanElement:false,SVGTests:false,SVGTextContentElement:false,SVGTextElement:false,SVGTextPathElement:false,SVGTextPositioningElement:false,SVGTitleElement:false,SVGTransform:false,SVGTransformList:false,SVGTransformable:false,SVGURIReference:false,SVGUnitTypes:false,SVGUseElement:false,SVGVKernElement:false,SVGViewElement:false,SVGViewSpec:false,SVGZoomAndPan:false,TextDecoder:false,TextEncoder:false,TimeEvent:false,top:false,URL:false,WebGLActiveInfo:false,WebGLBuffer:false,WebGLContextEvent:false,WebGLFramebuffer:false,WebGLProgram:false,WebGLRenderbuffer:false,WebGLRenderingContext:false,WebGLShader:false,WebGLShaderPrecisionFormat:false,WebGLTexture:false,WebGLUniformLocation:false,WebSocket:false,window:false,Worker:false,XDomainRequest:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false};exports.devel={alert:false,confirm:false,console:false,Debug:false,opera:false,prompt:false};exports.worker={importScripts:true,postMessage:true,self:true,FileReaderSync:true};exports.nonstandard={escape:false,unescape:false};exports.couch={require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false};exports.node={__filename:false,__dirname:false,GLOBAL:false,global:false,module:false,require:false,Buffer:true,console:true,exports:true,process:true,setTimeout:true,clearTimeout:true,setInterval:true,clearInterval:true,setImmediate:true,clearImmediate:true};exports.browserify={__filename:false,__dirname:false,global:false,module:false,require:false,Buffer:true,exports:true,process:true};exports.phantom={phantom:true,require:true,WebPage:true,console:true,exports:true};exports.qunit={asyncTest:false,deepEqual:false,equal:false,expect:false,module:false,notDeepEqual:false,notEqual:false,notPropEqual:false,notStrictEqual:false,ok:false,propEqual:false,QUnit:false,raises:false,start:false,stop:false,strictEqual:false,test:false,"throws":false};exports.rhino={defineClass:false,deserialize:false,gc:false,help:false,importClass:false,importPackage:false,java:false,load:false,loadClass:false,Packages:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false};exports.shelljs={target:false,echo:false,exit:false,cd:false,pwd:false,ls:false,find:false,cp:false,rm:false,mv:false,mkdir:false,test:false,cat:false,sed:false,grep:false,which:false,dirs:false,pushd:false,popd:false,env:false,exec:false,chmod:false,config:false,error:false,tempdir:false};exports.typed={ArrayBuffer:false,ArrayBufferView:false,DataView:false,Float32Array:false,Float64Array:false,Int16Array:false,Int32Array:false,Int8Array:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false};exports.wsh={ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true};exports.dojo={dojo:false,dijit:false,dojox:false,define:false,require:false};exports.jquery={$:false,jQuery:false};exports.mootools={$:false,$$:false,Asset:false,Browser:false,Chain:false,Class:false,Color:false,Cookie:false,Core:false,Document:false,DomReady:false,DOMEvent:false,DOMReady:false,Drag:false,Element:false,Elements:false,Event:false,Events:false,Fx:false,Group:false,Hash:false,HtmlTable:false,IFrame:false,IframeShim:false,InputValidator:false,instanceOf:false,Keyboard:false,Locale:false,Mask:false,MooTools:false,Native:false,Options:false,OverText:false,Request:false,Scroller:false,Slick:false,Slider:false,Sortables:false,Spinner:false,Swiff:false,Tips:false,Type:false,typeOf:false,URI:false,Window:false};exports.prototypejs={$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false};exports.yui={YUI:false,Y:false,YUI_config:false};exports.mocha={describe:false,it:false,before:false,after:false,beforeEach:false,afterEach:false,suite:false,test:false,setup:false,teardown:false};exports.jasmine={jasmine:false,describe:false,it:false,xit:false,beforeEach:false,afterEach:false,setFixtures:false,loadFixtures:false,spyOn:false,expect:false,runs:false,waitsFor:false,waits:false}},{}],121:[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={"&":"&","<":"<",">":">",'"':""","'":"'"};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:{})},{}],122:[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)},{}],123:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var isArray=types.builtInTypes.array;var b=types.builders;var n=types.namedTypes;var leap=require("./leap");var meta=require("./meta");var util=require("./util");var runtimeKeysMethod=util.runtimeProperty("keys");var hasOwn=Object.prototype.hasOwnProperty;function Emitter(contextId){assert.ok(this instanceof Emitter);n.Identifier.assert(contextId);Object.defineProperties(this,{contextId:{value:contextId},listing:{value:[]},marked:{value:[true]},finalLoc:{value:loc()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new leap.LeapManager(this)}})}var Ep=Emitter.prototype;exports.Emitter=Emitter;function loc(){return b.literal(-1)}Ep.mark=function(loc){n.Literal.assert(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};Ep.emit=function(node){if(n.Expression.check(node))node=b.expressionStatement(node);n.Statement.assert(node);this.listing.push(node)};Ep.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Ep.assign=function(lhs,rhs){return b.expressionStatement(b.assignmentExpression("=",lhs,rhs))};Ep.contextProperty=function(name,computed){return b.memberExpression(this.contextId,computed?b.literal(name):b.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Ep.isVolatileContextProperty=function(expr){if(n.MemberExpression.check(expr)){if(expr.computed){return true}if(n.Identifier.check(expr.object)&&n.Identifier.check(expr.property)&&expr.object.name===this.contextId.name&&hasOwn.call(volatileContextPropertyNames,expr.property.name)){return true}}return false};Ep.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Ep.setReturnValue=function(valuePath){n.Expression.assert(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Ep.clearPendingException=function(tryLoc,assignee){n.Literal.assert(tryLoc);var catchCall=b.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Ep.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(b.breakStatement())};Ep.jumpIf=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);this.emit(b.ifStatement(test,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};Ep.jumpIfNot=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);var negatedTest;if(n.UnaryExpression.check(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=b.unaryExpression("!",test)}this.emit(b.ifStatement(negatedTest,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};var nextTempId=0;Ep.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Ep.getContextFunction=function(id){return b.functionExpression(id||null,[this.contextId],b.blockStatement([this.getDispatchLoop()]),false,false)};Ep.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(b.switchCase(b.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(b.switchCase(this.finalLoc,[]),b.switchCase(b.literal("end"),[b.returnStatement(b.callExpression(this.contextProperty("stop"),[]))]));return b.whileStatement(b.literal(1),b.switchStatement(b.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return n.BreakStatement.check(stmt)||n.ContinueStatement.check(stmt)||n.ReturnStatement.check(stmt)||n.ThrowStatement.check(stmt)}Ep.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return b.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 b.arrayExpression(triple)}))};Ep.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.assert(node);if(n.Statement.check(node))return self.explodeStatement(path);if(n.Expression.check(node))return self.explodeExpression(path,ignoreResult);if(n.Declaration.check(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))}Ep.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;n.Statement.assert(stmt);if(labelId){n.Identifier.assert(labelId)}else{labelId=null}if(n.BlockStatement.check(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}switch(stmt.type){case"ExpressionStatement":self.explodeExpression(path.get("expression"),true);break;case"LabeledStatement":self.explodeStatement(path.get("body"),stmt.label);break;case"WhileStatement":var before=loc();var after=loc();self.mark(before);self.jumpIfNot(self.explodeExpression(path.get("test")),after);self.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(before);self.mark(after);break;case"DoWhileStatement":var first=loc();var test=loc();var after=loc();self.mark(first);self.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){self.explode(path.get("body"))});self.mark(test);self.jumpIf(self.explodeExpression(path.get("test")),first);self.mark(after);break;case"ForStatement":var head=loc();var update=loc();var after=loc();if(stmt.init){self.explode(path.get("init"),true)}self.mark(head);if(stmt.test){self.jumpIfNot(self.explodeExpression(path.get("test")),after)}else{}self.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){self.explodeStatement(path.get("body"))});self.mark(update);if(stmt.update){self.explode(path.get("update"),true)}self.jump(head);self.mark(after);break;case"ForInStatement":n.Identifier.assert(stmt.left);var head=loc();var after=loc();var keyIterNextFn=self.makeTempVar();self.emitAssign(keyIterNextFn,b.callExpression(runtimeKeysMethod,[self.explodeExpression(path.get("right"))]));self.mark(head);var keyInfoTmpVar=self.makeTempVar();self.jumpIf(b.memberExpression(b.assignmentExpression("=",keyInfoTmpVar,b.callExpression(keyIterNextFn,[])),b.identifier("done"),false),after);self.emitAssign(stmt.left,b.memberExpression(keyInfoTmpVar,b.identifier("value"),false));self.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(head);self.mark(after);break;case"BreakStatement":self.emitAbruptCompletion({type:"break",target:self.leapManager.getBreakLoc(stmt.label)});break;case"ContinueStatement":self.emitAbruptCompletion({type:"continue",target:self.leapManager.getContinueLoc(stmt.label)});break;case"SwitchStatement":var disc=self.emitAssign(self.makeTempVar(),self.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];n.SwitchCase.assert(c);if(c.test){condition=b.conditionalExpression(b.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}self.jump(self.explodeExpression(new types.NodePath(condition,path,"discriminant")));self.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var c=casePath.value;var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});self.mark(after);if(defaultLoc.value===-1){self.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}break;case"IfStatement":var elseLoc=stmt.alternate&&loc();var after=loc();self.jumpIfNot(self.explodeExpression(path.get("test")),elseLoc||after);self.explodeStatement(path.get("consequent"));if(elseLoc){self.jump(after);self.mark(elseLoc);self.explodeStatement(path.get("alternate"))}self.mark(after);break;case"ReturnStatement":self.emitAbruptCompletion({type:"return",value:self.explodeExpression(path.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var after=loc();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(self.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);self.tryEntries.push(tryEntry);self.updateContextPrevLoc(tryEntry.firstLoc);self.leapManager.withEntry(tryEntry,function(){self.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){self.jump(finallyLoc)}else{self.jump(after)}self.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=self.makeTempVar();self.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;n.CatchClause.assert(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(util.isReference(path,catchParamName)&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)},visitFunction:function(path){if(path.scope.declares(catchParamName)){return false}this.traverse(path)}});self.leapManager.withEntry(catchEntry,function(){self.explodeStatement(bodyPath)})}if(finallyLoc){self.updateContextPrevLoc(self.mark(finallyLoc));self.leapManager.withEntry(finallyEntry,function(){self.explodeStatement(path.get("finalizer"))});self.emit(b.callExpression(self.contextProperty("finish"),[finallyEntry.firstLoc]))}});self.mark(after);break;case"ThrowStatement":self.emit(b.throwStatement(self.explodeExpression(path.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Ep.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=[b.literal(record.type)];if(record.type==="break"||record.type==="continue"){n.Literal.assert(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){n.Expression.assert(record.value);abruptArgs[1]=record.value}}this.emit(b.returnStatement(b.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!hasOwn.call(record,"target")}if(type==="break"||type==="continue"){return!hasOwn.call(record,"value")&&n.Literal.check(record.target)}if(type==="return"||type==="throw"){return hasOwn.call(record,"value")&&!hasOwn.call(record,"target")}return false}Ep.getUnmarkedCurrentLoc=function(){return b.literal(this.listing.length)};Ep.updateContextPrevLoc=function(loc){if(loc){n.Literal.assert(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)};Ep.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){n.Expression.assert(expr)}else{return expr}var self=this;var result;function finish(expr){n.Expression.assert(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}switch(expr.type){case"MemberExpression":return finish(b.memberExpression(self.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed));case"CallExpression":var oldCalleePath=path.get("callee");var newCallee=self.explodeExpression(oldCalleePath);if(!n.MemberExpression.check(oldCalleePath.node)&&n.MemberExpression.check(newCallee)){newCallee=b.sequenceExpression([b.literal(0),newCallee])}return finish(b.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"NewExpression":return finish(b.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"ObjectExpression":return finish(b.objectExpression(path.get("properties").map(function(propPath){return b.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})));case"ArrayExpression":return finish(b.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})));case"SequenceExpression":var lastIndex=expr.expressions.length-1;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result;case"LogicalExpression":var after=loc();if(!ignoreResult){result=self.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){self.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");self.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);self.mark(after);return result;case"ConditionalExpression":var elseLoc=loc();var after=loc();var test=self.explodeExpression(path.get("test"));self.jumpIfNot(test,elseLoc);if(!ignoreResult){result=self.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);self.jump(after);self.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);self.mark(after);return result;case"UnaryExpression":return finish(b.unaryExpression(expr.operator,self.explodeExpression(path.get("argument")),!!expr.prefix));case"BinaryExpression":return finish(b.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))));case"AssignmentExpression":return finish(b.assignmentExpression(expr.operator,self.explodeExpression(path.get("left")),self.explodeExpression(path.get("right"))));case"UpdateExpression":return finish(b.updateExpression(expr.operator,self.explodeExpression(path.get("argument")),expr.prefix));case"YieldExpression":var after=loc();var arg=expr.argument&&self.explodeExpression(path.get("argument"));if(arg&&expr.delegate){var result=self.makeTempVar();self.emit(b.returnStatement(b.callExpression(self.contextProperty("delegateYield"),[arg,b.literal(result.property.name),after])));self.mark(after);return result}self.emitAssign(self.contextProperty("next"),after);self.emit(b.returnStatement(arg||null));self.mark(after);return self.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"./leap":125,"./meta":126,"./util":127,assert:90,recast:154}],124:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);n.Function.assert(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){n.VariableDeclaration.assert(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(b.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 b.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return b.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(n.VariableDeclaration.check(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(n.VariableDeclaration.check(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 parentNode=path.parent.node;var assignment=b.expressionStatement(b.assignmentExpression("=",node.id,b.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(n.BlockStatement.check(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(path){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(n.Identifier.check(param)){paramNames[param.name]=param
}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!hasOwn.call(paramNames,name)){declarations.push(b.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return b.variableDeclaration("var",declarations)}},{assert:90,recast:154}],125:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var n=types.namedTypes;var b=types.builders;var inherits=require("util").inherits;var hasOwn=Object.prototype.hasOwnProperty;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);n.Literal.assert(returnLoc);Object.defineProperties(this,{returnLoc:{value:returnLoc}})}inherits(FunctionEntry,Entry);exports.FunctionEntry=FunctionEntry;function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Literal.assert(continueLoc);if(label){n.Identifier.assert(label)}else{label=null}Object.defineProperties(this,{breakLoc:{value:breakLoc},continueLoc:{value:continueLoc},label:{value:label}})}inherits(LoopEntry,Entry);exports.LoopEntry=LoopEntry;function SwitchEntry(breakLoc){Entry.call(this);n.Literal.assert(breakLoc);Object.defineProperties(this,{breakLoc:{value:breakLoc}})}inherits(SwitchEntry,Entry);exports.SwitchEntry=SwitchEntry;function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);n.Literal.assert(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);Object.defineProperties(this,{firstLoc:{value:firstLoc},catchEntry:{value:catchEntry},finallyEntry:{value:finallyEntry}})}inherits(TryEntry,Entry);exports.TryEntry=TryEntry;function CatchEntry(firstLoc,paramId){Entry.call(this);n.Literal.assert(firstLoc);n.Identifier.assert(paramId);Object.defineProperties(this,{firstLoc:{value:firstLoc},paramId:{value:paramId}})}inherits(CatchEntry,Entry);exports.CatchEntry=CatchEntry;function FinallyEntry(firstLoc){Entry.call(this);n.Literal.assert(firstLoc);Object.defineProperties(this,{firstLoc:{value:firstLoc}})}inherits(FinallyEntry,Entry);exports.FinallyEntry=FinallyEntry;function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);Object.defineProperties(this,{emitter:{value:emitter},entryStack:{value:[new FunctionEntry(emitter.finalLoc)]}})}var LMp=LeapManager.prototype;exports.LeapManager=LeapManager;LMp.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)}};LMp._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};LMp.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LMp.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"./emit":123,assert:90,recast:154,util:114}],126:[function(require,module,exports){var assert=require("assert");var m=require("private").makeAccessor();var types=require("recast").types;var isArray=types.builtInTypes.array;var n=types.namedTypes;var hasOwn=Object.prototype.hasOwnProperty;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.assert(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.assert(node);var meta=m(node);if(hasOwn.call(meta,propertyName))return meta[propertyName];if(hasOwn.call(opaqueTypes,node.type))return meta[propertyName]=false;if(hasOwn.call(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(hasOwn.call(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:90,"private":122,recast:154}],127:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.defaults=function(obj){var len=arguments.length;var extension;for(var i=1;i<len;++i){if(extension=arguments[i]){for(var key in extension){if(hasOwn.call(extension,key)&&!hasOwn.call(obj,key)){obj[key]=extension[key]}}}}return obj};exports.runtimeProperty=function(name){return b.memberExpression(b.identifier("regeneratorRuntime"),b.identifier(name),false)};exports.isReference=function(path,name){var node=path.value;if(!n.Identifier.check(node)){return false}if(name&&node.name!==name){return false}var parent=path.parent.value;switch(parent.type){case"VariableDeclarator":return path.name==="init";case"MemberExpression":return path.name==="object"||parent.computed&&path.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(path.name==="id"){return false}if(parent.params===path.parentPath&&parent.params[path.name]===node){return false}return true;case"ClassDeclaration":case"ClassExpression":return path.name!=="id";case"CatchClause":return path.name!=="param";case"Property":case"MethodDefinition":return path.name!=="key";case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return false;default:return true}}},{assert:90,recast:154}],128:[function(require,module,exports){var assert=require("assert");var fs=require("fs");var recast=require("recast");var types=recast.types;var n=types.namedTypes;var b=types.builders;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var hoist=require("./hoist").hoist;var Emitter=require("./emit").Emitter;var runtimeProperty=require("./util").runtimeProperty;var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");var runtimeValuesMethod=runtimeProperty("values");var runtimeAsyncMethod=runtimeProperty("async");exports.transform=function transform(node,options){options=options||{};node=recast.visit(node,visitor);if(options.includeRuntime===true||options.includeRuntime==="if used"&&visitor.wasChangeReported()){injectRuntime(n.File.check(node)?node.program:node)}options.madeChanges=visitor.wasChangeReported();return node};function injectRuntime(program){n.Program.assert(program);var runtimePath=require("..").runtime.path;var runtime=fs.readFileSync(runtimePath,"utf8");var runtimeBody=recast.parse(runtime,{sourceFileName:runtimePath}).program.body;var body=program.body;body.unshift.apply(body,runtimeBody)}var visitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){this.traverse(path);var node=path.value;if(!node.generator&&!node.async){return}this.reportChanged();node.generator=false;if(node.expression){node.expression=false;node.body=b.blockStatement([b.returnStatement(node.body)])}if(node.async){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=path.scope.parent.declareTemporary("callee$"));var innerFnId=b.identifier(node.id.name+"$");var contextId=path.scope.declareTemporary("context$");var argsId=path.scope.declareTemporary("args$");var shouldAliasArguments=renameArguments(path,argsId);var vars=hoist(path);if(shouldAliasArguments){vars=vars||b.variableDeclaration("var",[]);vars.declarations.push(b.variableDeclarator(argsId,b.identifier("arguments")))}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?b.literal(null):outerFnId,b.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=b.callExpression(node.async?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(b.returnStatement(wrapCall));node.body=b.blockStatement(outerBody);if(node.async){node.async=false;return}if(n.FunctionDeclaration.check(node)){var pp=path.parent;while(pp&&!(n.BlockStatement.check(pp.value)||n.Program.check(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=b.variableDeclaration("var",[b.variableDeclarator(node.id,b.callExpression(runtimeMarkMethod,[node]))]);if(node.comments){varDecl.comments=node.comments;node.comments=null}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{n.FunctionExpression.assert(node);return b.callExpression(runtimeMarkMethod,[node])}},visitForOfStatement:function(path){this.traverse(path);var node=path.value;var tempIterId=path.scope.declareTemporary("t$");var tempIterDecl=b.variableDeclarator(tempIterId,b.callExpression(runtimeValuesMethod,[node.right]));var tempInfoId=path.scope.declareTemporary("t$");var tempInfoDecl=b.variableDeclarator(tempInfoId,null);var init=node.left;var loopId;if(n.VariableDeclaration.check(init)){loopId=init.declarations[0].id;init.declarations.push(tempIterDecl,tempInfoDecl)}else{loopId=init;init=b.variableDeclaration("var",[tempIterDecl,tempInfoDecl])}n.Identifier.assert(loopId);var loopIdAssignExprStmt=b.expressionStatement(b.assignmentExpression("=",loopId,b.memberExpression(tempInfoId,b.identifier("value"),false)));if(n.BlockStatement.check(node.body)){node.body.body.unshift(loopIdAssignExprStmt)}else{node.body=b.blockStatement([loopIdAssignExprStmt,node.body])}return b.forStatement(init,b.unaryExpression("!",b.memberExpression(b.assignmentExpression("=",tempInfoId,b.callExpression(b.memberExpression(tempIterId,b.identifier("next"),false),[])),b.identifier("done"),false)),null,node.body)}});function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;n.Statement.assert(value);if(n.ExpressionStatement.check(value)&&n.Literal.check(value.expression)&&value.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(n.CallExpression.check(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}function renameArguments(funcPath,argsId){assert.ok(funcPath instanceof types.NodePath);var func=funcPath.value;var didReplaceArguments=false;var hasImplicitArguments=false;recast.visit(funcPath,{visitFunction:function(path){if(path.value===func){hasImplicitArguments=!path.scope.lookup("arguments");this.traverse(path)}else{return false}},visitIdentifier:function(path){if(path.value.name==="arguments"){var isMemberProperty=n.MemberExpression.check(path.parent.node)&&path.name==="property"&&!path.parent.node.computed;if(!isMemberProperty){path.replace(argsId);didReplaceArguments=true;return false}}this.traverse(path)}});return didReplaceArguments&&hasImplicitArguments}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){return false},visitAwaitExpression:function(path){return b.yieldExpression(path.value.argument,false)}})},{"..":129,"./emit":123,"./hoist":124,"./util":127,assert:90,fs:89,recast:154}],129:[function(require,module,exports){(function(__dirname){var assert=require("assert");var path=require("path");var fs=require("fs");var through=require("through");var transform=require("./lib/visit").transform;var utils=require("./lib/util");var recast=require("recast");var types=recast.types;var genOrAsyncFunExp=/\bfunction\s*\*|\basync\b/;var blockBindingExp=/\b(let|const)\s+/;function exports(file,options){var data=[];return through(write,end);function write(buf){data.push(buf)}function end(){this.queue(compile(data.join(""),options).code);this.queue(null)}}module.exports=exports;function runtime(){require("./runtime")}exports.runtime=runtime;runtime.path=path.join(__dirname,"runtime.js");function compile(source,options){options=normalizeOptions(options);if(!genOrAsyncFunExp.test(source)){return{code:(options.includeRuntime===true?fs.readFileSync(runtime.path,"utf-8")+"\n":"")+source}}var recastOptions=getRecastOptions(options);var ast=recast.parse(source,recastOptions);var path=new types.NodePath(ast);var programPath=path.get("program");if(shouldVarify(source,options)){varifyAst(programPath.node)}transform(programPath,options);return recast.print(path,recastOptions)}function normalizeOptions(options){options=utils.defaults(options||{},{includeRuntime:false,supportBlockBinding:true});if(!options.esprima){options.esprima=require("esprima-fb")}assert.ok(/harmony/.test(options.esprima.version),"Bad esprima version: "+options.esprima.version);return options}function getRecastOptions(options){var recastOptions={range:true};function copy(name){if(name in options){recastOptions[name]=options[name]}}copy("esprima");copy("sourceFileName");copy("sourceMapName");copy("inputSourceMap");copy("sourceRoot");return recastOptions}function shouldVarify(source,options){var supportBlockBinding=!!options.supportBlockBinding;if(supportBlockBinding){if(!blockBindingExp.test(source)){supportBlockBinding=false}}return supportBlockBinding}function varify(source,options){var recastOptions=getRecastOptions(normalizeOptions(options));var ast=recast.parse(source,recastOptions);varifyAst(ast.program);return recast.print(ast,recastOptions).code}function varifyAst(ast){types.namedTypes.Program.assert(ast);var defsResult=require("defs")(ast,{ast:true,disallowUnknownReferences:false,disallowDuplicated:false,disallowVars:false,loopClosures:"iife"});if(defsResult.errors){throw new Error(defsResult.errors.join("\n"))}return ast}exports.varify=varify;exports.compile=compile;exports.transform=transform}).call(this,"/node_modules/regenerator")},{"./lib/util":127,"./lib/visit":128,"./runtime":156,assert:90,defs:130,"esprima-fb":144,fs:89,path:98,recast:154,through:155}],130:[function(require,module,exports){"use strict";var assert=require("assert");var is=require("simple-is");var fmt=require("simple-fmt");var stringmap=require("stringmap");var stringset=require("stringset");var alter=require("alter");var traverse=require("ast-traverse");var breakable=require("breakable");var Scope=require("./scope");var error=require("./error");var getline=error.getline;var options=require("./options");var Stats=require("./stats");var jshint_vars=require("./jshint_globals/vars.js");function isConstLet(kind){return is.someof(kind,["const","let"])}function isVarConstLet(kind){return is.someof(kind,["var","const","let"])}function isNonFunctionBlock(node){return node.type==="BlockStatement"&&is.noneof(node.$parent.type,["FunctionDeclaration","FunctionExpression"])}function isForWithConstLet(node){return node.type==="ForStatement"&&node.init&&node.init.type==="VariableDeclaration"&&isConstLet(node.init.kind)}function isForInOfWithConstLet(node){return isForInOf(node)&&node.left.type==="VariableDeclaration"&&isConstLet(node.left.kind)}function isForInOf(node){return is.someof(node.type,["ForInStatement","ForOfStatement"])}function isFunction(node){return is.someof(node.type,["FunctionDeclaration","FunctionExpression"])}function isLoop(node){return is.someof(node.type,["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"])}function isReference(node){var parent=node.$parent;return node.$refToScope||node.type==="Identifier"&&!(parent.type==="VariableDeclarator"&&parent.id===node)&&!(parent.type==="MemberExpression"&&parent.computed===false&&parent.property===node)&&!(parent.type==="Property"&&parent.key===node)&&!(parent.type==="LabeledStatement"&&parent.label===node)&&!(parent.type==="CatchClause"&&parent.param===node)&&!(isFunction(parent)&&parent.id===node)&&!(isFunction(parent)&&is.someof(node,parent.params))&&true}function isLvalue(node){return isReference(node)&&(node.$parent.type==="AssignmentExpression"&&node.$parent.left===node||node.$parent.type==="UpdateExpression"&&node.$parent.argument===node)}function createScopes(node,parent){assert(!node.$scope);node.$parent=parent;node.$scope=node.$parent?node.$parent.$scope:null;if(node.type==="Program"){node.$scope=new Scope({kind:"hoist",node:node,parent:null})}else if(isFunction(node)){node.$scope=new Scope({kind:"hoist",node:node,parent:node.$parent.$scope});if(node.id){assert(node.id.type==="Identifier");if(node.type==="FunctionDeclaration"){node.$parent.$scope.add(node.id.name,"fun",node.id,null)}else if(node.type==="FunctionExpression"){node.$scope.add(node.id.name,"fun",node.id,null)}else{assert(false)}}node.params.forEach(function(param){node.$scope.add(param.name,"param",param,null)})}else if(node.type==="VariableDeclaration"){assert(isVarConstLet(node.kind));node.declarations.forEach(function(declarator){assert(declarator.type==="VariableDeclarator");var name=declarator.id.name;if(options.disallowVars&&node.kind==="var"){error(getline(declarator),"var {0} is not allowed (use let or const)",name)}node.$scope.add(name,node.kind,declarator.id,declarator.range[1])})}else if(isForWithConstLet(node)||isForInOfWithConstLet(node)){node.$scope=new Scope({kind:"block",node:node,parent:node.$parent.$scope})}else if(isNonFunctionBlock(node)){node.$scope=new Scope({kind:"block",node:node,parent:node.$parent.$scope})}else if(node.type==="CatchClause"){var identifier=node.param;node.$scope=new Scope({kind:"catch-block",node:node,parent:node.$parent.$scope});node.$scope.add(identifier.name,"caught",identifier,null);node.$scope.closestHoistScope().markPropagates(identifier.name)}}function createTopScope(programScope,environments,globals){function inject(obj){for(var name in obj){var writeable=obj[name];var kind=writeable?"var":"const";if(topScope.hasOwn(name)){topScope.remove(name)}topScope.add(name,kind,{loc:{start:{line:-1}}},-1)}}var topScope=new Scope({kind:"hoist",node:{},parent:null});var complementary={undefined:false,Infinity:false,console:false};inject(complementary);inject(jshint_vars.reservedVars);inject(jshint_vars.ecmaIdentifiers);if(environments){environments.forEach(function(env){if(!jshint_vars[env]){error(-1,'environment "{0}" not found',env)}else{inject(jshint_vars[env])}})}if(globals){inject(globals)}programScope.parent=topScope;topScope.children.push(programScope);return topScope}function setupReferences(ast,allIdentifiers,opts){var analyze=is.own(opts,"analyze")?opts.analyze:true;function visit(node){if(!isReference(node)){return}allIdentifiers.add(node.name);var scope=node.$scope.lookup(node.name);if(analyze&&!scope&&options.disallowUnknownReferences){error(getline(node),"reference to unknown global variable {0}",node.name)}if(analyze&&scope&&is.someof(scope.getKind(node.name),["const","let"])){var allowedFromPos=scope.getFromPos(node.name);var referencedAtPos=node.range[0];assert(is.finitenumber(allowedFromPos));assert(is.finitenumber(referencedAtPos));if(referencedAtPos<allowedFromPos){if(!node.$scope.hasFunctionScopeBetween(scope)){error(getline(node),"{0} is referenced before its declaration",node.name)}}}node.$refToScope=scope}traverse(ast,{pre:visit})}function varify(ast,stats,allIdentifiers,changes){function unique(name){assert(allIdentifiers.has(name));for(var cnt=0;;cnt++){var genName=name+"$"+String(cnt);if(!allIdentifiers.has(genName)){return genName}}}function renameDeclarations(node){if(node.type==="VariableDeclaration"&&isConstLet(node.kind)){var hoistScope=node.$scope.closestHoistScope();var origScope=node.$scope;changes.push({start:node.range[0],end:node.range[0]+node.kind.length,str:"var"});node.declarations.forEach(function(declarator){assert(declarator.type==="VariableDeclarator");var name=declarator.id.name;stats.declarator(node.kind);var rename=origScope!==hoistScope&&(hoistScope.hasOwn(name)||hoistScope.doesPropagate(name));var newName=rename?unique(name):name;origScope.remove(name);hoistScope.add(newName,"var",declarator.id,declarator.range[1]);origScope.moves=origScope.moves||stringmap();origScope.moves.set(name,{name:newName,scope:hoistScope});allIdentifiers.add(newName);if(newName!==name){stats.rename(name,newName,getline(declarator));declarator.id.originalName=name;declarator.id.name=newName;changes.push({start:declarator.id.range[0],end:declarator.id.range[1],str:newName})}});node.kind="var"}}function renameReferences(node){if(!node.$refToScope){return}var move=node.$refToScope.moves&&node.$refToScope.moves.get(node.name);if(!move){return}node.$refToScope=move.scope;if(node.name!==move.name){node.originalName=node.name;node.name=move.name;if(node.alterop){var existingOp=null;for(var i=0;i<changes.length;i++){var op=changes[i];if(op.node===node){existingOp=op;break}}assert(existingOp);existingOp.str=move.name}else{changes.push({start:node.range[0],end:node.range[1],str:move.name})}}}traverse(ast,{pre:renameDeclarations});traverse(ast,{pre:renameReferences});ast.$scope.traverse({pre:function(scope){delete scope.moves}})}function detectLoopClosures(ast){traverse(ast,{pre:visit});function detectIifyBodyBlockers(body,node){return breakable(function(brk){traverse(body,{pre:function(n){if(isFunction(n)){return false}var err=true;var msg="loop-variable {0} is captured by a loop-closure that can't be transformed due to use of {1} at line {2}";if(n.type==="BreakStatement"){error(getline(node),msg,node.name,"break",getline(n))}else if(n.type==="ContinueStatement"){error(getline(node),msg,node.name,"continue",getline(n))}else if(n.type==="ReturnStatement"){error(getline(node),msg,node.name,"return",getline(n))}else if(n.type==="YieldExpression"){error(getline(node),msg,node.name,"yield",getline(n))}else if(n.type==="Identifier"&&n.name==="arguments"){error(getline(node),msg,node.name,"arguments",getline(n))}else if(n.type==="VariableDeclaration"&&n.kind==="var"){error(getline(node),msg,node.name,"var",getline(n))}else{err=false}if(err){brk(true)}}});return false})}function visit(node){var loopNode=null;if(isReference(node)&&node.$refToScope&&isConstLet(node.$refToScope.getKind(node.name))){for(var n=node.$refToScope.node;;){if(isFunction(n)){return}else if(isLoop(n)){loopNode=n;break}n=n.$parent;if(!n){return}}assert(isLoop(loopNode));var defScope=node.$refToScope;var generateIIFE=options.loopClosures==="iife";for(var s=node.$scope;s;s=s.parent){if(s===defScope){return}else if(isFunction(s.node)){if(!generateIIFE){var msg='loop-variable {0} is captured by a loop-closure. Tried "loopClosures": "iife" in defs-config.json?';return error(getline(node),msg,node.name)}if(loopNode.type==="ForStatement"&&defScope.node===loopNode){var declarationNode=defScope.getNode(node.name);return error(getline(declarationNode),"Not yet specced ES6 feature. {0} is declared in for-loop header and then captured in loop closure",declarationNode.name)}if(detectIifyBodyBlockers(loopNode.body,node)){return}loopNode.$iify=true}}}}}function transformLoopClosures(root,ops,options){function insertOp(pos,str,node){var op={start:pos,end:pos,str:str};if(node){op.node=node}ops.push(op)}traverse(root,{pre:function(node){if(!node.$iify){return}var hasBlock=node.body.type==="BlockStatement";var insertHead=hasBlock?node.body.range[0]+1:node.body.range[0];var insertFoot=hasBlock?node.body.range[1]-1:node.body.range[1];var forInName=isForInOf(node)&&node.left.declarations[0].id.name;var iifeHead=fmt("(function({0}){",forInName?forInName:"");var iifeTail=fmt("}).call(this{0});",forInName?", "+forInName:"");var iifeFragment=options.parse(iifeHead+iifeTail);var iifeExpressionStatement=iifeFragment.body[0];var iifeBlockStatement=iifeExpressionStatement.expression.callee.object.body;if(hasBlock){var forBlockStatement=node.body;var tmp=forBlockStatement.body;forBlockStatement.body=[iifeExpressionStatement];iifeBlockStatement.body=tmp}else{var tmp$0=node.body;node.body=iifeExpressionStatement;iifeBlockStatement.body[0]=tmp$0}insertOp(insertHead,iifeHead);if(forInName){insertOp(insertFoot,"}).call(this, ");var args=iifeExpressionStatement.expression.arguments;var iifeArgumentIdentifier=args[1];iifeArgumentIdentifier.alterop=true;insertOp(insertFoot,forInName,iifeArgumentIdentifier);insertOp(insertFoot,");")}else{insertOp(insertFoot,iifeTail)}}})}function detectConstAssignment(ast){traverse(ast,{pre:function(node){if(isLvalue(node)){var scope=node.$scope.lookup(node.name);if(scope&&scope.getKind(node.name)==="const"){error(getline(node),"can't assign to const variable {0}",node.name)}}}})}function detectConstantLets(ast){traverse(ast,{pre:function(node){if(isLvalue(node)){var scope=node.$scope.lookup(node.name);if(scope){scope.markWrite(node.name)}}}});ast.$scope.detectUnmodifiedLets()}function setupScopeAndReferences(root,opts){traverse(root,{pre:createScopes});var topScope=createTopScope(root.$scope,options.environments,options.globals);var allIdentifiers=stringset();topScope.traverse({pre:function(scope){allIdentifiers.addMany(scope.decls.keys())}});setupReferences(root,allIdentifiers,opts);return allIdentifiers}function cleanupTree(root){traverse(root,{pre:function(node){for(var prop in node){if(prop[0]==="$"){delete node[prop]}}}})}function run(src,config){for(var key in config){options[key]=config[key]}var parsed;if(is.object(src)){if(!options.ast){return{errors:["Can't produce string output when input is an AST. "+"Did you forget to set options.ast = true?"]}}parsed=src}else if(is.string(src)){try{parsed=options.parse(src,{loc:true,range:true})}catch(e){return{errors:[fmt("line {0} column {1}: Error during input file parsing\n{2}\n{3}",e.lineNumber,e.column,src.split("\n")[e.lineNumber-1],fmt.repeat(" ",e.column-1)+"^")]}}}else{return{errors:["Input was neither an AST object nor a string."]}}var ast=parsed;error.reset();var allIdentifiers=setupScopeAndReferences(ast,{});detectLoopClosures(ast);detectConstAssignment(ast);var changes=[];transformLoopClosures(ast,changes,options);if(error.errors.length>=1){return{errors:error.errors}}if(changes.length>0){cleanupTree(ast);allIdentifiers=setupScopeAndReferences(ast,{analyze:false})}assert(error.errors.length===0);var stats=new Stats;varify(ast,stats,allIdentifiers,changes);if(options.ast){cleanupTree(ast);return{stats:stats,ast:ast}}else{var transformedSrc=alter(src,changes);return{stats:stats,src:transformedSrc}}}module.exports=run},{"./error":131,"./jshint_globals/vars.js":132,"./options":133,"./scope":134,"./stats":135,alter:136,assert:90,"ast-traverse":138,breakable:139,"simple-fmt":140,"simple-is":141,stringmap:142,stringset:143}],131:[function(require,module,exports){"use strict";var fmt=require("simple-fmt");var assert=require("assert");function error(line,var_args){assert(arguments.length>=2);var msg=arguments.length===2?String(var_args):fmt.apply(fmt,Array.prototype.slice.call(arguments,1));error.errors.push(line===-1?msg:fmt("line {0}: {1}",line,msg))}error.reset=function(){error.errors=[]};error.getline=function(node){if(node&&node.loc&&node.loc.start){return node.loc.start.line}return-1};error.reset();module.exports=error},{assert:90,"simple-fmt":140}],132:[function(require,module,exports){"use strict";exports.reservedVars={arguments:false,NaN:false};exports.ecmaIdentifiers={Array:false,Boolean:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Function:false,hasOwnProperty:false,isFinite:false,isNaN:false,JSON:false,Math:false,Map:false,Number:false,Object:false,parseInt:false,parseFloat:false,RangeError:false,ReferenceError:false,RegExp:false,Set:false,String:false,SyntaxError:false,TypeError:false,URIError:false,WeakMap:false};exports.browser={ArrayBuffer:false,ArrayBufferView:false,Audio:false,Blob:false,addEventListener:false,applicationCache:false,atob:false,blur:false,btoa:false,clearInterval:false,clearTimeout:false,close:false,closed:false,DataView:false,DOMParser:false,defaultStatus:false,document:false,Element:false,event:false,FileReader:false,Float32Array:false,Float64Array:false,FormData:false,focus:false,frames:false,getComputedStyle:false,HTMLElement:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,history:false,Int16Array:false,Int32Array:false,Int8Array:false,Image:false,length:false,localStorage:false,location:false,MessageChannel:false,MessageEvent:false,MessagePort:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,Node:false,NodeFilter:false,navigator:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,Option:false,parent:false,print:false,removeEventListener:false,resizeBy:false,resizeTo:false,screen:false,scroll:false,scrollBy:false,scrollTo:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,status:false,top:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false,WebSocket:false,window:false,Worker:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false};exports.devel={alert:false,confirm:false,console:false,Debug:false,opera:false,prompt:false};exports.worker={importScripts:true,postMessage:true,self:true};exports.nonstandard={escape:false,unescape:false};exports.couch={require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false};exports.node={__filename:false,__dirname:false,Buffer:false,DataView:false,console:false,exports:true,GLOBAL:false,global:false,module:false,process:false,require:false,setTimeout:false,clearTimeout:false,setInterval:false,clearInterval:false};exports.phantom={phantom:true,require:true,WebPage:true};exports.rhino={defineClass:false,deserialize:false,gc:false,help:false,importPackage:false,java:false,load:false,loadClass:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false};exports.wsh={ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true};
exports.dojo={dojo:false,dijit:false,dojox:false,define:false,require:false};exports.jquery={$:false,jQuery:false};exports.mootools={$:false,$$:false,Asset:false,Browser:false,Chain:false,Class:false,Color:false,Cookie:false,Core:false,Document:false,DomReady:false,DOMEvent:false,DOMReady:false,Drag:false,Element:false,Elements:false,Event:false,Events:false,Fx:false,Group:false,Hash:false,HtmlTable:false,Iframe:false,IframeShim:false,InputValidator:false,instanceOf:false,Keyboard:false,Locale:false,Mask:false,MooTools:false,Native:false,Options:false,OverText:false,Request:false,Scroller:false,Slick:false,Slider:false,Sortables:false,Spinner:false,Swiff:false,Tips:false,Type:false,typeOf:false,URI:false,Window:false};exports.prototypejs={$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false};exports.yui={YUI:false,Y:false,YUI_config:false}},{}],133:[function(require,module,exports){module.exports={disallowVars:false,disallowDuplicated:true,disallowUnknownReferences:true,parse:require("esprima-fb").parse}},{"esprima-fb":144}],134:[function(require,module,exports){"use strict";var assert=require("assert");var stringmap=require("stringmap");var stringset=require("stringset");var is=require("simple-is");var fmt=require("simple-fmt");var error=require("./error");var getline=error.getline;var options=require("./options");function Scope(args){assert(is.someof(args.kind,["hoist","block","catch-block"]));assert(is.object(args.node));assert(args.parent===null||is.object(args.parent));this.kind=args.kind;this.node=args.node;this.parent=args.parent;this.children=[];this.decls=stringmap();this.written=stringset();this.propagates=this.kind==="hoist"?stringset():null;if(this.parent){this.parent.children.push(this)}}Scope.prototype.print=function(indent){indent=indent||0;var scope=this;var names=this.decls.keys().map(function(name){return fmt("{0} [{1}]",name,scope.decls.get(name).kind)}).join(", ");var propagates=this.propagates?this.propagates.items().join(", "):"";console.log(fmt("{0}{1}: {2}. propagates: {3}",fmt.repeat(" ",indent),this.node.type,names,propagates));this.children.forEach(function(c){c.print(indent+2)})};Scope.prototype.add=function(name,kind,node,referableFromPos){assert(is.someof(kind,["fun","param","var","caught","const","let"]));function isConstLet(kind){return is.someof(kind,["const","let"])}var scope=this;if(is.someof(kind,["fun","param","var"])){while(scope.kind!=="hoist"){if(scope.decls.has(name)&&isConstLet(scope.decls.get(name).kind)){return error(getline(node),"{0} is already declared",name)}scope=scope.parent}}if(scope.decls.has(name)&&(options.disallowDuplicated||isConstLet(scope.decls.get(name).kind)||isConstLet(kind))){return error(getline(node),"{0} is already declared",name)}var declaration={kind:kind,node:node};if(referableFromPos){assert(is.someof(kind,["var","const","let"]));declaration.from=referableFromPos}scope.decls.set(name,declaration)};Scope.prototype.getKind=function(name){assert(is.string(name));var decl=this.decls.get(name);return decl?decl.kind:null};Scope.prototype.getNode=function(name){assert(is.string(name));var decl=this.decls.get(name);return decl?decl.node:null};Scope.prototype.getFromPos=function(name){assert(is.string(name));var decl=this.decls.get(name);return decl?decl.from:null};Scope.prototype.hasOwn=function(name){return this.decls.has(name)};Scope.prototype.remove=function(name){return this.decls.remove(name)};Scope.prototype.doesPropagate=function(name){return this.propagates.has(name)};Scope.prototype.markPropagates=function(name){this.propagates.add(name)};Scope.prototype.closestHoistScope=function(){var scope=this;while(scope.kind!=="hoist"){scope=scope.parent}return scope};Scope.prototype.hasFunctionScopeBetween=function(outer){function isFunction(node){return is.someof(node.type,["FunctionDeclaration","FunctionExpression"])}for(var scope=this;scope;scope=scope.parent){if(scope===outer){return false}if(isFunction(scope.node)){return true}}throw new Error("wasn't inner scope of outer")};Scope.prototype.lookup=function(name){for(var scope=this;scope;scope=scope.parent){if(scope.decls.has(name)){return scope}else if(scope.kind==="hoist"){scope.propagates.add(name)}}return null};Scope.prototype.markWrite=function(name){assert(is.string(name));this.written.add(name)};Scope.prototype.detectUnmodifiedLets=function(){var outmost=this;function detect(scope){if(scope!==outmost){scope.decls.keys().forEach(function(name){if(scope.getKind(name)==="let"&&!scope.written.has(name)){return error(getline(scope.getNode(name)),"{0} is declared as let but never modified so could be const",name)}})}scope.children.forEach(function(childScope){detect(childScope)})}detect(this)};Scope.prototype.traverse=function(options){options=options||{};var pre=options.pre;var post=options.post;function visit(scope){if(pre){pre(scope)}scope.children.forEach(function(childScope){visit(childScope)});if(post){post(scope)}}visit(this)};module.exports=Scope},{"./error":131,"./options":133,assert:90,"simple-fmt":140,"simple-is":141,stringmap:142,stringset:143}],135:[function(require,module,exports){var fmt=require("simple-fmt");var is=require("simple-is");var assert=require("assert");function Stats(){this.lets=0;this.consts=0;this.renames=[]}Stats.prototype.declarator=function(kind){assert(is.someof(kind,["const","let"]));if(kind==="const"){this.consts++}else{this.lets++}};Stats.prototype.rename=function(oldName,newName,line){this.renames.push({oldName:oldName,newName:newName,line:line})};Stats.prototype.toString=function(){var renames=this.renames.map(function(r){return r}).sort(function(a,b){return a.line-b.line});var renameStr=renames.map(function(rename){return fmt("\nline {0}: {1} => {2}",rename.line,rename.oldName,rename.newName)}).join("");var sum=this.consts+this.lets;var constlets=sum===0?"can't calculate const coverage (0 consts, 0 lets)":fmt("{0}% const coverage ({1} consts, {2} lets)",Math.floor(100*this.consts/sum),this.consts,this.lets);return constlets+renameStr+"\n"};module.exports=Stats},{assert:90,"simple-fmt":140,"simple-is":141}],136:[function(require,module,exports){var assert=require("assert");var stableSort=require("stable");function alter(str,fragments){"use strict";var isArray=Array.isArray||function(v){return Object.prototype.toString.call(v)==="[object Array]"};assert(typeof str==="string");assert(isArray(fragments));var sortedFragments=stableSort(fragments,function(a,b){return a.start-b.start});var outs=[];var pos=0;for(var i=0;i<sortedFragments.length;i++){var frag=sortedFragments[i];assert(pos<=frag.start);assert(frag.start<=frag.end);outs.push(str.slice(pos,frag.start));outs.push(frag.str);pos=frag.end}if(pos<str.length){outs.push(str.slice(pos))}return outs.join("")}if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=alter}},{assert:90,stable:137}],137:[function(require,module,exports){(function(){var stable=function(arr,comp){return exec(arr.slice(),comp)};stable.inplace=function(arr,comp){var result=exec(arr,comp);if(result!==arr){pass(result,null,arr.length,arr)}return arr};function exec(arr,comp){if(typeof comp!=="function"){comp=function(a,b){return String(a).localeCompare(b)}}var len=arr.length;if(len<=1){return arr}var buffer=new Array(len);for(var chk=1;chk<len;chk*=2){pass(arr,comp,chk,buffer);var tmp=arr;arr=buffer;buffer=tmp}return arr}var pass=function(arr,comp,chk,result){var len=arr.length;var i=0;var dbl=chk*2;var l,r,e;var li,ri;for(l=0;l<len;l+=dbl){r=l+chk;e=r+chk;if(r>len)r=len;if(e>len)e=len;li=l;ri=r;while(true){if(li<r&&ri<e){if(comp(arr[li],arr[ri])<=0){result[i++]=arr[li++]}else{result[i++]=arr[ri++]}}else if(li<r){result[i++]=arr[li++]}else if(ri<e){result[i++]=arr[ri++]}else{break}}}};if(typeof module!=="undefined"){module.exports=stable}else{window.stable=stable}})()},{}],138:[function(require,module,exports){function traverse(root,options){"use strict";options=options||{};var pre=options.pre;var post=options.post;var skipProperty=options.skipProperty;function visit(node,parent,prop,idx){if(!node||typeof node.type!=="string"){return}var res=undefined;if(pre){res=pre(node,parent,prop,idx)}if(res!==false){for(var prop in node){if(skipProperty?skipProperty(prop,node):prop[0]==="$"){continue}var child=node[prop];if(Array.isArray(child)){for(var i=0;i<child.length;i++){visit(child[i],node,prop,i)}}else{visit(child,node,prop)}}}if(post){post(node,parent,prop,idx)}}visit(root,null)}if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=traverse}},{}],139:[function(require,module,exports){var breakable=function(){"use strict";function Val(val,brk){this.val=val;this.brk=brk}function make_brk(){return function brk(val){throw new Val(val,brk)}}function breakable(fn){var brk=make_brk();try{return fn(brk)}catch(e){if(e instanceof Val&&e.brk===brk){return e.val}throw e}}return breakable}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=breakable}},{}],140:[function(require,module,exports){var fmt=function(){"use strict";function fmt(str,var_args){var args=Array.prototype.slice.call(arguments,1);return str.replace(/\{(\d+)\}/g,function(s,match){return match in args?args[match]:s})}function obj(str,obj){return str.replace(/\{([_$a-zA-Z0-9][_$a-zA-Z0-9]*)\}/g,function(s,match){return match in obj?obj[match]:s})}function repeat(str,n){return new Array(n+1).join(str)}fmt.fmt=fmt;fmt.obj=obj;fmt.repeat=repeat;return fmt}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=fmt}},{}],141:[function(require,module,exports){var is=function(){"use strict";var hasOwnProperty=Object.prototype.hasOwnProperty;var toString=Object.prototype.toString;var _undefined=void 0;return{nan:function(v){return v!==v},"boolean":function(v){return typeof v==="boolean"},number:function(v){return typeof v==="number"},string:function(v){return typeof v==="string"},fn:function(v){return typeof v==="function"},object:function(v){return v!==null&&typeof v==="object"},primitive:function(v){var t=typeof v;return v===null||v===_undefined||t==="boolean"||t==="number"||t==="string"},array:Array.isArray||function(v){return toString.call(v)==="[object Array]"},finitenumber:function(v){return typeof v==="number"&&isFinite(v)},someof:function(v,values){return values.indexOf(v)>=0},noneof:function(v,values){return values.indexOf(v)===-1},own:function(obj,prop){return hasOwnProperty.call(obj,prop)}}}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=is}},{}],142:[function(require,module,exports){var StringMap=function(){"use strict";var hasOwnProperty=Object.prototype.hasOwnProperty;var create=function(){function hasOwnEnumerableProps(obj){for(var prop in obj){if(hasOwnProperty.call(obj,prop)){return true}}return false}function hasOwnPollutedProps(obj){return hasOwnProperty.call(obj,"__count__")||hasOwnProperty.call(obj,"__parent__")}var useObjectCreate=false;if(typeof Object.create==="function"){if(!hasOwnEnumerableProps(Object.create(null))){useObjectCreate=true}}if(useObjectCreate===false){if(hasOwnEnumerableProps({})){throw new Error("StringMap environment error 0, please file a bug at https://github.com/olov/stringmap/issues")}}var o=useObjectCreate?Object.create(null):{};var useProtoClear=false;if(hasOwnPollutedProps(o)){o.__proto__=null;if(hasOwnEnumerableProps(o)||hasOwnPollutedProps(o)){throw new Error("StringMap environment error 1, please file a bug at https://github.com/olov/stringmap/issues")}useProtoClear=true}return function(){var o=useObjectCreate?Object.create(null):{};if(useProtoClear){o.__proto__=null}return o}}();function stringmap(optional_object){if(!(this instanceof stringmap)){return new stringmap(optional_object)}this.obj=create();this.hasProto=false;this.proto=undefined;if(optional_object){this.setMany(optional_object)}}stringmap.prototype.has=function(key){if(typeof key!=="string"){throw new Error("StringMap expected string key")}return key==="__proto__"?this.hasProto:hasOwnProperty.call(this.obj,key)};stringmap.prototype.get=function(key){if(typeof key!=="string"){throw new Error("StringMap expected string key")}return key==="__proto__"?this.proto:hasOwnProperty.call(this.obj,key)?this.obj[key]:undefined};stringmap.prototype.set=function(key,value){if(typeof key!=="string"){throw new Error("StringMap expected string key")}if(key==="__proto__"){this.hasProto=true;this.proto=value}else{this.obj[key]=value}};stringmap.prototype.remove=function(key){if(typeof key!=="string"){throw new Error("StringMap expected string key")}var didExist=this.has(key);if(key==="__proto__"){this.hasProto=false;this.proto=undefined}else{delete this.obj[key]}return didExist};stringmap.prototype["delete"]=stringmap.prototype.remove;stringmap.prototype.isEmpty=function(){for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){return false}}return!this.hasProto};stringmap.prototype.size=function(){var len=0;for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){++len}}return this.hasProto?len+1:len};stringmap.prototype.keys=function(){var keys=[];for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){keys.push(key)}}if(this.hasProto){keys.push("__proto__")}return keys};stringmap.prototype.values=function(){var values=[];for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){values.push(this.obj[key])}}if(this.hasProto){values.push(this.proto)}return values};stringmap.prototype.items=function(){var items=[];for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){items.push([key,this.obj[key]])}}if(this.hasProto){items.push(["__proto__",this.proto])}return items};stringmap.prototype.setMany=function(object){if(object===null||typeof object!=="object"&&typeof object!=="function"){throw new Error("StringMap expected Object")}for(var key in object){if(hasOwnProperty.call(object,key)){this.set(key,object[key])}}return this};stringmap.prototype.merge=function(other){var keys=other.keys();for(var i=0;i<keys.length;i++){var key=keys[i];this.set(key,other.get(key))}return this};stringmap.prototype.map=function(fn){var keys=this.keys();for(var i=0;i<keys.length;i++){var key=keys[i];keys[i]=fn(this.get(key),key)}return keys};stringmap.prototype.forEach=function(fn){var keys=this.keys();for(var i=0;i<keys.length;i++){var key=keys[i];fn(this.get(key),key)}};stringmap.prototype.clone=function(){var other=stringmap();return other.merge(this)};stringmap.prototype.toString=function(){var self=this;return"{"+this.keys().map(function(key){return JSON.stringify(key)+":"+JSON.stringify(self.get(key))}).join(",")+"}"};return stringmap}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=StringMap}},{}],143:[function(require,module,exports){var StringSet=function(){"use strict";var hasOwnProperty=Object.prototype.hasOwnProperty;var create=function(){function hasOwnEnumerableProps(obj){for(var prop in obj){if(hasOwnProperty.call(obj,prop)){return true}}return false}function hasOwnPollutedProps(obj){return hasOwnProperty.call(obj,"__count__")||hasOwnProperty.call(obj,"__parent__")}var useObjectCreate=false;if(typeof Object.create==="function"){if(!hasOwnEnumerableProps(Object.create(null))){useObjectCreate=true}}if(useObjectCreate===false){if(hasOwnEnumerableProps({})){throw new Error("StringSet environment error 0, please file a bug at https://github.com/olov/stringset/issues")}}var o=useObjectCreate?Object.create(null):{};var useProtoClear=false;if(hasOwnPollutedProps(o)){o.__proto__=null;if(hasOwnEnumerableProps(o)||hasOwnPollutedProps(o)){throw new Error("StringSet environment error 1, please file a bug at https://github.com/olov/stringset/issues")}useProtoClear=true}return function(){var o=useObjectCreate?Object.create(null):{};if(useProtoClear){o.__proto__=null}return o}}();function stringset(optional_array){if(!(this instanceof stringset)){return new stringset(optional_array)}this.obj=create();this.hasProto=false;if(optional_array){this.addMany(optional_array)}}stringset.prototype.has=function(item){if(typeof item!=="string"){throw new Error("StringSet expected string item")}return item==="__proto__"?this.hasProto:hasOwnProperty.call(this.obj,item)};stringset.prototype.add=function(item){if(typeof item!=="string"){throw new Error("StringSet expected string item")}if(item==="__proto__"){this.hasProto=true}else{this.obj[item]=true}};stringset.prototype.remove=function(item){if(typeof item!=="string"){throw new Error("StringSet expected string item")}var didExist=this.has(item);if(item==="__proto__"){this.hasProto=false}else{delete this.obj[item]}return didExist};stringset.prototype["delete"]=stringset.prototype.remove;stringset.prototype.isEmpty=function(){for(var item in this.obj){if(hasOwnProperty.call(this.obj,item)){return false}}return!this.hasProto};stringset.prototype.size=function(){var len=0;for(var item in this.obj){if(hasOwnProperty.call(this.obj,item)){++len}}return this.hasProto?len+1:len};stringset.prototype.items=function(){var items=[];for(var item in this.obj){if(hasOwnProperty.call(this.obj,item)){items.push(item)}}if(this.hasProto){items.push("__proto__")}return items};stringset.prototype.addMany=function(items){if(!Array.isArray(items)){throw new Error("StringSet expected array")}for(var i=0;i<items.length;i++){this.add(items[i])}return this};stringset.prototype.merge=function(other){this.addMany(other.items());return this};stringset.prototype.clone=function(){var other=stringset();return other.merge(this)};stringset.prototype.toString=function(){return"{"+this.items().map(JSON.stringify).join(",")+"}"};return stringset}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=StringSet}},{}],144:[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.esprima={})}})(this,function(exports){"use strict";var Token,TokenName,FnExprTokens,Syntax,PropertyKind,Messages,Regex,SyntaxTreeDelegate,XHTMLEntities,ClassPropertyType,source,strict,index,lineNumber,lineStart,length,delegate,lookahead,state,extra;Token={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8,RegularExpression:9,Template:10,XJSIdentifier:11,XJSText:12};TokenName={};TokenName[Token.BooleanLiteral]="Boolean";TokenName[Token.EOF]="<end>";TokenName[Token.Identifier]="Identifier";TokenName[Token.Keyword]="Keyword";TokenName[Token.NullLiteral]="Null";TokenName[Token.NumericLiteral]="Numeric";TokenName[Token.Punctuator]="Punctuator";TokenName[Token.StringLiteral]="String";TokenName[Token.XJSIdentifier]="XJSIdentifier";TokenName[Token.XJSText]="XJSText";TokenName[Token.RegularExpression]="RegularExpression";FnExprTokens=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="];Syntax={AnyTypeAnnotation:"AnyTypeAnnotation",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrayTypeAnnotation:"ArrayTypeAnnotation",ArrowFunctionExpression:"ArrowFunctionExpression",AssignmentExpression:"AssignmentExpression",BinaryExpression:"BinaryExpression",BlockStatement:"BlockStatement",BooleanTypeAnnotation:"BooleanTypeAnnotation",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ClassImplements:"ClassImplements",ClassProperty:"ClassProperty",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DeclareClass:"DeclareClass",DeclareFunction:"DeclareFunction",DeclareModule:"DeclareModule",DeclareVariable:"DeclareVariable",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportDeclaration:"ExportDeclaration",ExportBatchSpecifier:"ExportBatchSpecifier",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",ForStatement:"ForStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",FunctionTypeAnnotation:"FunctionTypeAnnotation",FunctionTypeParam:"FunctionTypeParam",GenericTypeAnnotation:"GenericTypeAnnotation",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",InterfaceDeclaration:"InterfaceDeclaration",InterfaceExtends:"InterfaceExtends",IntersectionTypeAnnotation:"IntersectionTypeAnnotation",LabeledStatement:"LabeledStatement",Literal:"Literal",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",NullableTypeAnnotation:"NullableTypeAnnotation",NumberTypeAnnotation:"NumberTypeAnnotation",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",ObjectTypeAnnotation:"ObjectTypeAnnotation",ObjectTypeCallProperty:"ObjectTypeCallProperty",ObjectTypeIndexer:"ObjectTypeIndexer",ObjectTypeProperty:"ObjectTypeProperty",Program:"Program",Property:"Property",QualifiedTypeIdentifier:"QualifiedTypeIdentifier",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SpreadProperty:"SpreadProperty",StringLiteralTypeAnnotation:"StringLiteralTypeAnnotation",StringTypeAnnotation:"StringTypeAnnotation",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TupleTypeAnnotation:"TupleTypeAnnotation",TryStatement:"TryStatement",TypeAlias:"TypeAlias",TypeAnnotation:"TypeAnnotation",TypeofTypeAnnotation:"TypeofTypeAnnotation",TypeParameterDeclaration:"TypeParameterDeclaration",TypeParameterInstantiation:"TypeParameterInstantiation",UnaryExpression:"UnaryExpression",UnionTypeAnnotation:"UnionTypeAnnotation",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",VoidTypeAnnotation:"VoidTypeAnnotation",WhileStatement:"WhileStatement",WithStatement:"WithStatement",XJSIdentifier:"XJSIdentifier",XJSNamespacedName:"XJSNamespacedName",XJSMemberExpression:"XJSMemberExpression",XJSEmptyExpression:"XJSEmptyExpression",XJSExpressionContainer:"XJSExpressionContainer",XJSElement:"XJSElement",XJSClosingElement:"XJSClosingElement",XJSOpeningElement:"XJSOpeningElement",XJSAttribute:"XJSAttribute",XJSSpreadAttribute:"XJSSpreadAttribute",XJSText:"XJSText",YieldExpression:"YieldExpression",AwaitExpression:"AwaitExpression"};PropertyKind={Data:1,Get:2,Set:4};ClassPropertyType={"static":"static",prototype:"prototype"};Messages={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedTemplate:"Unexpected quasi %0",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInFormalsList:"Invalid left-hand side in formals list",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalDuplicateClassProperty:"Illegal duplicate property in class definition",IllegalReturn:"Illegal return statement",IllegalSpread:"Illegal spread element",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",ParameterAfterRestParameter:"Rest parameter must be final parameter of an argument list",DefaultRestParameter:"Rest parameter can not have a default value",ElementAfterSpreadElement:"Spread must be the final element of an element list",PropertyAfterSpreadProperty:"A rest property must be the final property of an object literal",ObjectPatternAsRestParameter:"Invalid rest parameter",ObjectPatternAsSpread:"Invalid spread argument",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode",MissingFromClause:"Missing from clause",NoAsAfterImportNamespace:"Missing as after import *",InvalidModuleSpecifier:"Invalid module specifier",NoUnintializedConst:"Const must be initialized",ComprehensionRequiresBlock:"Comprehension must have at least one block",ComprehensionError:"Comprehension Error",EachNotAllowed:"Each is not supported",InvalidXJSAttributeValue:"XJS value should be either an expression or a quoted XJS text",ExpectedXJSClosingTag:"Expected corresponding XJS closing tag for %0",AdjacentXJSElements:"Adjacent XJS elements must be wrapped in an enclosing tag",ConfusedAboutFunctionType:"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType"};Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),LeadingZeros:new RegExp("^0+(?!$)")};function assert(condition,message){if(!condition){throw new Error("ASSERT: "+message)}}function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return"0123456789abcdefABCDEF".indexOf(ch)>=0}function isOctalDigit(ch){return"01234567".indexOf(ch)>=0}function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&" ".indexOf(String.fromCharCode(ch))>0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function isFutureReservedWord(id){switch(id){case"class":case"enum":case"export":case"extends":case"import":case"super":return true;default:return false}}function isStrictModeReservedWord(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return true;default:return false}}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isKeyword(id){if(strict&&isStrictModeReservedWord(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"||id==="let";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==="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 skipComment(){var ch,blockComment,lineComment;blockComment=false;lineComment=false;while(index<length){ch=source.charCodeAt(index);if(lineComment){++index;if(isLineTerminator(ch)){lineComment=false;if(ch===13&&source.charCodeAt(index)===10){++index}++lineNumber;lineStart=index}}else if(blockComment){if(isLineTerminator(ch)){if(ch===13){++index}if(ch!==13||source.charCodeAt(index)===10){++lineNumber;++index;lineStart=index;if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}}else{ch=source.charCodeAt(index++);if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")
}if(ch===42){ch=source.charCodeAt(index);if(ch===47){++index;blockComment=false}}}}else if(ch===47){ch=source.charCodeAt(index+1);if(ch===47){index+=2;lineComment=true}else if(ch===42){index+=2;blockComment=true;if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}else{break}}else if(isWhiteSpace(ch)){++index}else if(isLineTerminator(ch)){++index;if(ch===13&&source.charCodeAt(index)===10){++index}++lineNumber;lineStart=index}else{break}}}function scanHexEscape(prefix){var i,len,ch,code=0;len=prefix==="u"?4:2;for(i=0;i<len;++i){if(index<length&&isHexDigit(source[index])){ch=source[index++];code=code*16+"0123456789abcdef".indexOf(ch.toLowerCase())}else{return""}}return String.fromCharCode(code)}function scanUnicodeCodePointEscape(){var ch,code,cu1,cu2;ch=source[index];code=0;if(ch==="}"){throwError({},Messages.UnexpectedToken,"ILLEGAL")}while(index<length){ch=source[index++];if(!isHexDigit(ch)){break}code=code*16+"0123456789abcdef".indexOf(ch.toLowerCase())}if(code>1114111||ch!=="}"){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(code<=65535){return String.fromCharCode(code)}cu1=(code-65536>>10)+55296;cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function getEscapedIdentifier(){var ch,id;ch=source.charCodeAt(index++);id=String.fromCharCode(ch);if(ch===92){if(source.charCodeAt(index)!==117){throwError({},Messages.UnexpectedToken,"ILLEGAL")}++index;ch=scanHexEscape("u");if(!ch||ch==="\\"||!isIdentifierStart(ch.charCodeAt(0))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}id=ch}while(index<length){ch=source.charCodeAt(index);if(!isIdentifierPart(ch)){break}++index;id+=String.fromCharCode(ch);if(ch===92){id=id.substr(0,id.length-1);if(source.charCodeAt(index)!==117){throwError({},Messages.UnexpectedToken,"ILLEGAL")}++index;ch=scanHexEscape("u");if(!ch||ch==="\\"||!isIdentifierPart(ch.charCodeAt(0))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}id+=ch}}return id}function getIdentifier(){var start,ch;start=index++;while(index<length){ch=source.charCodeAt(index);if(ch===92){index=start;return getEscapedIdentifier()}if(isIdentifierPart(ch)){++index}else{break}}return source.slice(start,index)}function scanIdentifier(){var start,id,type;start=index;id=source.charCodeAt(index)===92?getEscapedIdentifier():getIdentifier();if(id.length===1){type=Token.Identifier}else if(isKeyword(id)){type=Token.Keyword}else if(id==="null"){type=Token.NullLiteral}else if(id==="true"||id==="false"){type=Token.BooleanLiteral}else{type=Token.Identifier}return{type:type,value:id,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanPunctuator(){var start=index,code=source.charCodeAt(index),code2,ch1=source[index],ch2,ch3,ch4;switch(code){case 40:case 41:case 59:case 44:case 123:case 125:case 91:case 93:case 58:case 63:case 126:++index;if(extra.tokenize){if(code===40){extra.openParenToken=extra.tokens.length}else if(code===123){extra.openCurlyToken=extra.tokens.length}}return{type:Token.Punctuator,value:String.fromCharCode(code),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]};default:code2=source.charCodeAt(index+1);if(code2===61){switch(code){case 37:case 38:case 42:case 43:case 45:case 47:case 60:case 62:case 94:case 124:index+=2;return{type:Token.Punctuator,value:String.fromCharCode(code)+String.fromCharCode(code2),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]};case 33:case 61:index+=2;if(source.charCodeAt(index)===61){++index}return{type:Token.Punctuator,value:source.slice(start,index),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]};default:break}}break}ch2=source[index+1];ch3=source[index+2];ch4=source[index+3];if(ch1===">"&&ch2===">"&&ch3===">"){if(ch4==="="){index+=4;return{type:Token.Punctuator,value:">>>=",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}}if(ch1===">"&&ch2===">"&&ch3===">"){index+=3;return{type:Token.Punctuator,value:">>>",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="<"&&ch2==="<"&&ch3==="="){index+=3;return{type:Token.Punctuator,value:"<<=",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1===">"&&ch2===">"&&ch3==="="){index+=3;return{type:Token.Punctuator,value:">>=",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="."&&ch2==="."&&ch3==="."){index+=3;return{type:Token.Punctuator,value:"...",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1===ch2&&"+-<>&|".indexOf(ch1)>=0&&!state.inType){index+=2;return{type:Token.Punctuator,value:ch1+ch2,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="="&&ch2===">"){index+=2;return{type:Token.Punctuator,value:"=>",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if("<>=!+-*%&|^/".indexOf(ch1)>=0){++index;return{type:Token.Punctuator,value:ch1,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="."){++index;return{type:Token.Punctuator,value:ch1,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}throwError({},Messages.UnexpectedToken,"ILLEGAL")}function scanHexLiteral(start){var number="";while(index<length){if(!isHexDigit(source[index])){break}number+=source[index++]}if(number.length===0){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(isIdentifierStart(source.charCodeAt(index))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.NumericLiteral,value:parseInt("0x"+number,16),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanOctalLiteral(prefix,start){var number,octal;if(isOctalDigit(prefix)){octal=true;number="0"+source[index++]}else{octal=false;++index;number=""}while(index<length){if(!isOctalDigit(source[index])){break}number+=source[index++]}if(!octal&&number.length===0){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(isIdentifierStart(source.charCodeAt(index))||isDecimalDigit(source.charCodeAt(index))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.NumericLiteral,value:parseInt(number,8),octal:octal,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanNumericLiteral(){var number,start,ch,octal;ch=source[index];assert(isDecimalDigit(ch.charCodeAt(0))||ch===".","Numeric literal must start with a decimal digit or a decimal point");start=index;number="";if(ch!=="."){number=source[index++];ch=source[index];if(number==="0"){if(ch==="x"||ch==="X"){++index;return scanHexLiteral(start)}if(ch==="b"||ch==="B"){++index;number="";while(index<length){ch=source[index];if(ch!=="0"&&ch!=="1"){break}number+=source[index++]}if(number.length===0){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(index<length){ch=source.charCodeAt(index);if(isIdentifierStart(ch)||isDecimalDigit(ch)){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}return{type:Token.NumericLiteral,value:parseInt(number,2),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch==="o"||ch==="O"||isOctalDigit(ch)){return scanOctalLiteral(ch,start)}if(ch&&isDecimalDigit(ch.charCodeAt(0))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++]}ch=source[index]}if(ch==="."){number+=source[index++];while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++]}ch=source[index]}if(ch==="e"||ch==="E"){number+=source[index++];ch=source[index];if(ch==="+"||ch==="-"){number+=source[index++]}if(isDecimalDigit(source.charCodeAt(index))){while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++]}}else{throwError({},Messages.UnexpectedToken,"ILLEGAL")}}if(isIdentifierStart(source.charCodeAt(index))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.NumericLiteral,value:parseFloat(number),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanStringLiteral(){var str="",quote,start,ch,code,unescaped,restore,octal=false;quote=source[index];assert(quote==="'"||quote==='"',"String literal must starts with a quote");start=index;++index;while(index<length){ch=source[index++];if(ch===quote){quote="";break}else if(ch==="\\"){ch=source[index++];if(!ch||!isLineTerminator(ch.charCodeAt(0))){switch(ch){case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+=" ";break;case"u":case"x":if(source[index]==="{"){++index;str+=scanUnicodeCodePointEscape()}else{restore=index;unescaped=scanHexEscape(ch);if(unescaped){str+=unescaped}else{index=restore;str+=ch}}break;case"b":str+="\b";break;case"f":str+="\f";break;case"v":str+="";break;default:if(isOctalDigit(ch)){code="01234567".indexOf(ch);if(code!==0){octal=true}if(index<length&&isOctalDigit(source[index])){octal=true;code=code*8+"01234567".indexOf(source[index++]);if("0123".indexOf(ch)>=0&&index<length&&isOctalDigit(source[index])){code=code*8+"01234567".indexOf(source[index++])}}str+=String.fromCharCode(code)}else{str+=ch}break}}else{++lineNumber;if(ch==="\r"&&source[index]==="\n"){++index}lineStart=index}}else if(isLineTerminator(ch.charCodeAt(0))){break}else{str+=ch}}if(quote!==""){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.StringLiteral,value:str,octal:octal,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanTemplate(){var cooked="",ch,start,terminated,tail,restore,unescaped,code,octal;terminated=false;tail=false;start=index;++index;while(index<length){ch=source[index++];if(ch==="`"){tail=true;terminated=true;break}else if(ch==="$"){if(source[index]==="{"){++index;terminated=true;break}cooked+=ch}else if(ch==="\\"){ch=source[index++];if(!isLineTerminator(ch.charCodeAt(0))){switch(ch){case"n":cooked+="\n";break;case"r":cooked+="\r";break;case"t":cooked+=" ";break;case"u":case"x":if(source[index]==="{"){++index;cooked+=scanUnicodeCodePointEscape()}else{restore=index;unescaped=scanHexEscape(ch);if(unescaped){cooked+=unescaped}else{index=restore;cooked+=ch}}break;case"b":cooked+="\b";break;case"f":cooked+="\f";break;case"v":cooked+="";break;default:if(isOctalDigit(ch)){code="01234567".indexOf(ch);if(code!==0){octal=true}if(index<length&&isOctalDigit(source[index])){octal=true;code=code*8+"01234567".indexOf(source[index++]);if("0123".indexOf(ch)>=0&&index<length&&isOctalDigit(source[index])){code=code*8+"01234567".indexOf(source[index++])}}cooked+=String.fromCharCode(code)}else{cooked+=ch}break}}else{++lineNumber;if(ch==="\r"&&source[index]==="\n"){++index}lineStart=index}}else if(isLineTerminator(ch.charCodeAt(0))){++lineNumber;if(ch==="\r"&&source[index]==="\n"){++index}lineStart=index;cooked+="\n"}else{cooked+=ch}}if(!terminated){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.Template,value:{cooked:cooked,raw:source.slice(start+1,index-(tail?1:2))},tail:tail,octal:octal,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanTemplateElement(option){var startsWith,template;lookahead=null;skipComment();startsWith=option.head?"`":"}";if(source[index]!==startsWith){throwError({},Messages.UnexpectedToken,"ILLEGAL")}template=scanTemplate();peek();return template}function scanRegExp(){var str,ch,start,pattern,flags,value,classMarker=false,restore,terminated=false,tmp;lookahead=null;skipComment();start=index;ch=source[index];assert(ch==="/","Regular expression literal must start with a slash");str=source[index++];while(index<length){ch=source[index++];str+=ch;if(classMarker){if(ch==="]"){classMarker=false}}else{if(ch==="\\"){ch=source[index++];if(isLineTerminator(ch.charCodeAt(0))){throwError({},Messages.UnterminatedRegExp)}str+=ch}else if(ch==="/"){terminated=true;break}else if(ch==="["){classMarker=true}else if(isLineTerminator(ch.charCodeAt(0))){throwError({},Messages.UnterminatedRegExp)}}}if(!terminated){throwError({},Messages.UnterminatedRegExp)}pattern=str.substr(1,str.length-2);flags="";while(index<length){ch=source[index];if(!isIdentifierPart(ch.charCodeAt(0))){break}++index;if(ch==="\\"&&index<length){ch=source[index];if(ch==="u"){++index;restore=index;ch=scanHexEscape("u");if(ch){flags+=ch;for(str+="\\u";restore<index;++restore){str+=source[restore]}}else{index=restore;flags+="u";str+="\\u"}}else{str+="\\"}}else{flags+=ch;str+=ch}}tmp=pattern;if(flags.indexOf("u")>=0){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}try{value=new RegExp(tmp)}catch(e){throwError({},Messages.InvalidRegExp)}try{value=new RegExp(pattern,flags)}catch(exception){value=null}peek();if(extra.tokenize){return{type:Token.RegularExpression,value:value,regex:{pattern:pattern,flags:flags},lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}return{literal:str,value:value,regex:{pattern:pattern,flags:flags},range:[start,index]}}function isIdentifierName(token){return token.type===Token.Identifier||token.type===Token.Keyword||token.type===Token.BooleanLiteral||token.type===Token.NullLiteral}function advanceSlash(){var prevToken,checkToken;prevToken=extra.tokens[extra.tokens.length-1];if(!prevToken){return scanRegExp()}if(prevToken.type==="Punctuator"){if(prevToken.value===")"){checkToken=extra.tokens[extra.openParenToken-1];if(checkToken&&checkToken.type==="Keyword"&&(checkToken.value==="if"||checkToken.value==="while"||checkToken.value==="for"||checkToken.value==="with")){return scanRegExp()}return scanPunctuator()}if(prevToken.value==="}"){if(extra.tokens[extra.openCurlyToken-3]&&extra.tokens[extra.openCurlyToken-3].type==="Keyword"){checkToken=extra.tokens[extra.openCurlyToken-4];if(!checkToken){return scanPunctuator()}}else if(extra.tokens[extra.openCurlyToken-4]&&extra.tokens[extra.openCurlyToken-4].type==="Keyword"){checkToken=extra.tokens[extra.openCurlyToken-5];if(!checkToken){return scanRegExp()}}else{return scanPunctuator()}if(FnExprTokens.indexOf(checkToken.value)>=0){return scanPunctuator()}return scanRegExp()}return scanRegExp()}if(prevToken.type==="Keyword"){return scanRegExp()}return scanPunctuator()}function advance(){var ch;if(!state.inXJSChild){skipComment()}if(index>=length){return{type:Token.EOF,lineNumber:lineNumber,lineStart:lineStart,range:[index,index]}}if(state.inXJSChild){return advanceXJSChild()}ch=source.charCodeAt(index);if(ch===40||ch===41||ch===58){return scanPunctuator()}if(ch===39||ch===34){if(state.inXJSTag){return scanXJSStringLiteral()}return scanStringLiteral()}if(state.inXJSTag&&isXJSIdentifierStart(ch)){return scanXJSIdentifier()}if(ch===96){return scanTemplate()}if(isIdentifierStart(ch)){return scanIdentifier()}if(ch===46){if(isDecimalDigit(source.charCodeAt(index+1))){return scanNumericLiteral()}return scanPunctuator()}if(isDecimalDigit(ch)){return scanNumericLiteral()}if(extra.tokenize&&ch===47){return advanceSlash()}return scanPunctuator()}function lex(){var token;token=lookahead;index=token.range[1];lineNumber=token.lineNumber;lineStart=token.lineStart;lookahead=advance();index=token.range[1];lineNumber=token.lineNumber;lineStart=token.lineStart;return token}function peek(){var pos,line,start;pos=index;line=lineNumber;start=lineStart;lookahead=advance();index=pos;lineNumber=line;lineStart=start}function lookahead2(){var adv,pos,line,start,result;adv=typeof extra.advance==="function"?extra.advance:advance;pos=index;line=lineNumber;start=lineStart;if(lookahead===null){lookahead=adv()}index=lookahead.range[1];lineNumber=lookahead.lineNumber;lineStart=lookahead.lineStart;result=adv();index=pos;lineNumber=line;lineStart=start;return result}function rewind(token){index=token.range[0];lineNumber=token.lineNumber;lineStart=token.lineStart;lookahead=token}function markerCreate(){if(!extra.loc&&!extra.range){return undefined}skipComment();return{offset:index,line:lineNumber,col:index-lineStart}}function markerCreatePreserveWhitespace(){if(!extra.loc&&!extra.range){return undefined}return{offset:index,line:lineNumber,col:index-lineStart}}function processComment(node){var lastChild,trailingComments,bottomRight=extra.bottomRightStack,last=bottomRight[bottomRight.length-1];if(node.type===Syntax.Program){if(node.body.length>0){return}}if(extra.trailingComments.length>0){if(extra.trailingComments[0].range[0]>=node.range[1]){trailingComments=extra.trailingComments;extra.trailingComments=[]}else{extra.trailingComments.length=0}}else{if(last&&last.trailingComments&&last.trailingComments[0].range[0]>=node.range[1]){trailingComments=last.trailingComments;delete last.trailingComments}}if(last){while(last&&last.range[0]>=node.range[0]){lastChild=last;last=bottomRight.pop()}}if(lastChild){if(lastChild.leadingComments&&lastChild.leadingComments[lastChild.leadingComments.length-1].range[1]<=node.range[0]){node.leadingComments=lastChild.leadingComments;delete lastChild.leadingComments}}else if(extra.leadingComments.length>0&&extra.leadingComments[extra.leadingComments.length-1].range[1]<=node.range[0]){node.leadingComments=extra.leadingComments;extra.leadingComments=[]}if(trailingComments){node.trailingComments=trailingComments}bottomRight.push(node)}function markerApply(marker,node){if(extra.range){node.range=[marker.offset,index]}if(extra.loc){node.loc={start:{line:marker.line,column:marker.col},end:{line:lineNumber,column:index-lineStart}};node=delegate.postProcess(node)}if(extra.attachComment){processComment(node)}return node}SyntaxTreeDelegate={name:"SyntaxTree",postProcess:function(node){return node},createArrayExpression:function(elements){return{type:Syntax.ArrayExpression,elements:elements}},createAssignmentExpression:function(operator,left,right){return{type:Syntax.AssignmentExpression,operator:operator,left:left,right:right}},createBinaryExpression:function(operator,left,right){var type=operator==="||"||operator==="&&"?Syntax.LogicalExpression:Syntax.BinaryExpression;return{type:type,operator:operator,left:left,right:right}},createBlockStatement:function(body){return{type:Syntax.BlockStatement,body:body}},createBreakStatement:function(label){return{type:Syntax.BreakStatement,label:label}},createCallExpression:function(callee,args){return{type:Syntax.CallExpression,callee:callee,arguments:args}},createCatchClause:function(param,body){return{type:Syntax.CatchClause,param:param,body:body}},createConditionalExpression:function(test,consequent,alternate){return{type:Syntax.ConditionalExpression,test:test,consequent:consequent,alternate:alternate}},createContinueStatement:function(label){return{type:Syntax.ContinueStatement,label:label}},createDebuggerStatement:function(){return{type:Syntax.DebuggerStatement}},createDoWhileStatement:function(body,test){return{type:Syntax.DoWhileStatement,body:body,test:test}},createEmptyStatement:function(){return{type:Syntax.EmptyStatement}},createExpressionStatement:function(expression){return{type:Syntax.ExpressionStatement,expression:expression}},createForStatement:function(init,test,update,body){return{type:Syntax.ForStatement,init:init,test:test,update:update,body:body}},createForInStatement:function(left,right,body){return{type:Syntax.ForInStatement,left:left,right:right,body:body,each:false}},createForOfStatement:function(left,right,body){return{type:Syntax.ForOfStatement,left:left,right:right,body:body}},createFunctionDeclaration:function(id,params,defaults,body,rest,generator,expression,isAsync,returnType,typeParameters){var funDecl={type:Syntax.FunctionDeclaration,id:id,params:params,defaults:defaults,body:body,rest:rest,generator:generator,expression:expression,returnType:returnType,typeParameters:typeParameters};if(isAsync){funDecl.async=true}return funDecl},createFunctionExpression:function(id,params,defaults,body,rest,generator,expression,isAsync,returnType,typeParameters){var funExpr={type:Syntax.FunctionExpression,id:id,params:params,defaults:defaults,body:body,rest:rest,generator:generator,expression:expression,returnType:returnType,typeParameters:typeParameters};if(isAsync){funExpr.async=true}return funExpr},createIdentifier:function(name){return{type:Syntax.Identifier,name:name,typeAnnotation:undefined,optional:undefined}},createTypeAnnotation:function(typeAnnotation){return{type:Syntax.TypeAnnotation,typeAnnotation:typeAnnotation}},createFunctionTypeAnnotation:function(params,returnType,rest,typeParameters){return{type:Syntax.FunctionTypeAnnotation,params:params,returnType:returnType,rest:rest,typeParameters:typeParameters}},createFunctionTypeParam:function(name,typeAnnotation,optional){return{type:Syntax.FunctionTypeParam,name:name,typeAnnotation:typeAnnotation,optional:optional}},createNullableTypeAnnotation:function(typeAnnotation){return{type:Syntax.NullableTypeAnnotation,typeAnnotation:typeAnnotation}},createArrayTypeAnnotation:function(elementType){return{type:Syntax.ArrayTypeAnnotation,elementType:elementType}},createGenericTypeAnnotation:function(id,typeParameters){return{type:Syntax.GenericTypeAnnotation,id:id,typeParameters:typeParameters}},createQualifiedTypeIdentifier:function(qualification,id){return{type:Syntax.QualifiedTypeIdentifier,qualification:qualification,id:id}},createTypeParameterDeclaration:function(params){return{type:Syntax.TypeParameterDeclaration,params:params}},createTypeParameterInstantiation:function(params){return{type:Syntax.TypeParameterInstantiation,params:params}},createAnyTypeAnnotation:function(){return{type:Syntax.AnyTypeAnnotation}},createBooleanTypeAnnotation:function(){return{type:Syntax.BooleanTypeAnnotation}},createNumberTypeAnnotation:function(){return{type:Syntax.NumberTypeAnnotation}},createStringTypeAnnotation:function(){return{type:Syntax.StringTypeAnnotation}},createStringLiteralTypeAnnotation:function(token){return{type:Syntax.StringLiteralTypeAnnotation,value:token.value,raw:source.slice(token.range[0],token.range[1])}},createVoidTypeAnnotation:function(){return{type:Syntax.VoidTypeAnnotation}},createTypeofTypeAnnotation:function(argument){return{type:Syntax.TypeofTypeAnnotation,argument:argument}},createTupleTypeAnnotation:function(types){return{type:Syntax.TupleTypeAnnotation,types:types}},createObjectTypeAnnotation:function(properties,indexers,callProperties){return{type:Syntax.ObjectTypeAnnotation,properties:properties,indexers:indexers,callProperties:callProperties}},createObjectTypeIndexer:function(id,key,value,isStatic){return{type:Syntax.ObjectTypeIndexer,id:id,key:key,value:value,"static":isStatic}},createObjectTypeCallProperty:function(value,isStatic){return{type:Syntax.ObjectTypeCallProperty,value:value,"static":isStatic}},createObjectTypeProperty:function(key,value,optional,isStatic){return{type:Syntax.ObjectTypeProperty,key:key,value:value,optional:optional,"static":isStatic}},createUnionTypeAnnotation:function(types){return{type:Syntax.UnionTypeAnnotation,types:types}},createIntersectionTypeAnnotation:function(types){return{type:Syntax.IntersectionTypeAnnotation,types:types}},createTypeAlias:function(id,typeParameters,right){return{type:Syntax.TypeAlias,id:id,typeParameters:typeParameters,right:right}},createInterface:function(id,typeParameters,body,extended){return{type:Syntax.InterfaceDeclaration,id:id,typeParameters:typeParameters,body:body,"extends":extended}},createInterfaceExtends:function(id,typeParameters){return{type:Syntax.InterfaceExtends,id:id,typeParameters:typeParameters}},createDeclareFunction:function(id){return{type:Syntax.DeclareFunction,id:id}},createDeclareVariable:function(id){return{type:Syntax.DeclareVariable,id:id}},createDeclareModule:function(id,body){return{type:Syntax.DeclareModule,id:id,body:body}},createXJSAttribute:function(name,value){return{type:Syntax.XJSAttribute,name:name,value:value||null}},createXJSSpreadAttribute:function(argument){return{type:Syntax.XJSSpreadAttribute,argument:argument}},createXJSIdentifier:function(name){return{type:Syntax.XJSIdentifier,name:name}},createXJSNamespacedName:function(namespace,name){return{type:Syntax.XJSNamespacedName,namespace:namespace,name:name}},createXJSMemberExpression:function(object,property){return{type:Syntax.XJSMemberExpression,object:object,property:property}},createXJSElement:function(openingElement,closingElement,children){return{type:Syntax.XJSElement,openingElement:openingElement,closingElement:closingElement,children:children}},createXJSEmptyExpression:function(){return{type:Syntax.XJSEmptyExpression}},createXJSExpressionContainer:function(expression){return{type:Syntax.XJSExpressionContainer,expression:expression}},createXJSOpeningElement:function(name,attributes,selfClosing){return{type:Syntax.XJSOpeningElement,name:name,selfClosing:selfClosing,attributes:attributes}},createXJSClosingElement:function(name){return{type:Syntax.XJSClosingElement,name:name}},createIfStatement:function(test,consequent,alternate){return{type:Syntax.IfStatement,test:test,consequent:consequent,alternate:alternate}},createLabeledStatement:function(label,body){return{type:Syntax.LabeledStatement,label:label,body:body}},createLiteral:function(token){var object={type:Syntax.Literal,value:token.value,raw:source.slice(token.range[0],token.range[1])};if(token.regex){object.regex=token.regex}return object},createMemberExpression:function(accessor,object,property){return{type:Syntax.MemberExpression,computed:accessor==="[",object:object,property:property}},createNewExpression:function(callee,args){return{type:Syntax.NewExpression,callee:callee,arguments:args}},createObjectExpression:function(properties){return{type:Syntax.ObjectExpression,properties:properties}},createPostfixExpression:function(operator,argument){return{type:Syntax.UpdateExpression,operator:operator,argument:argument,prefix:false}},createProgram:function(body){return{type:Syntax.Program,body:body}},createProperty:function(kind,key,value,method,shorthand,computed){return{type:Syntax.Property,key:key,value:value,kind:kind,method:method,shorthand:shorthand,computed:computed}},createReturnStatement:function(argument){return{type:Syntax.ReturnStatement,argument:argument}},createSequenceExpression:function(expressions){return{type:Syntax.SequenceExpression,expressions:expressions}},createSwitchCase:function(test,consequent){return{type:Syntax.SwitchCase,test:test,consequent:consequent}},createSwitchStatement:function(discriminant,cases){return{type:Syntax.SwitchStatement,discriminant:discriminant,cases:cases}},createThisExpression:function(){return{type:Syntax.ThisExpression}},createThrowStatement:function(argument){return{type:Syntax.ThrowStatement,argument:argument}},createTryStatement:function(block,guardedHandlers,handlers,finalizer){return{type:Syntax.TryStatement,block:block,guardedHandlers:guardedHandlers,handlers:handlers,finalizer:finalizer}},createUnaryExpression:function(operator,argument){if(operator==="++"||operator==="--"){return{type:Syntax.UpdateExpression,operator:operator,argument:argument,prefix:true}}return{type:Syntax.UnaryExpression,operator:operator,argument:argument,prefix:true}},createVariableDeclaration:function(declarations,kind){return{type:Syntax.VariableDeclaration,declarations:declarations,kind:kind}},createVariableDeclarator:function(id,init){return{type:Syntax.VariableDeclarator,id:id,init:init}},createWhileStatement:function(test,body){return{type:Syntax.WhileStatement,test:test,body:body}},createWithStatement:function(object,body){return{type:Syntax.WithStatement,object:object,body:body}},createTemplateElement:function(value,tail){return{type:Syntax.TemplateElement,value:value,tail:tail}},createTemplateLiteral:function(quasis,expressions){return{type:Syntax.TemplateLiteral,quasis:quasis,expressions:expressions}},createSpreadElement:function(argument){return{type:Syntax.SpreadElement,argument:argument}},createSpreadProperty:function(argument){return{type:Syntax.SpreadProperty,argument:argument}},createTaggedTemplateExpression:function(tag,quasi){return{type:Syntax.TaggedTemplateExpression,tag:tag,quasi:quasi}},createArrowFunctionExpression:function(params,defaults,body,rest,expression,isAsync){var arrowExpr={type:Syntax.ArrowFunctionExpression,id:null,params:params,defaults:defaults,body:body,rest:rest,generator:false,expression:expression};if(isAsync){arrowExpr.async=true}return arrowExpr},createMethodDefinition:function(propertyType,kind,key,value){return{type:Syntax.MethodDefinition,key:key,value:value,kind:kind,"static":propertyType===ClassPropertyType.static}},createClassProperty:function(key,typeAnnotation,computed,isStatic){return{type:Syntax.ClassProperty,key:key,typeAnnotation:typeAnnotation,computed:computed,"static":isStatic}},createClassBody:function(body){return{type:Syntax.ClassBody,body:body}},createClassImplements:function(id,typeParameters){return{type:Syntax.ClassImplements,id:id,typeParameters:typeParameters}},createClassExpression:function(id,superClass,body,typeParameters,superTypeParameters,implemented){return{type:Syntax.ClassExpression,id:id,superClass:superClass,body:body,typeParameters:typeParameters,superTypeParameters:superTypeParameters,"implements":implemented}},createClassDeclaration:function(id,superClass,body,typeParameters,superTypeParameters,implemented){return{type:Syntax.ClassDeclaration,id:id,superClass:superClass,body:body,typeParameters:typeParameters,superTypeParameters:superTypeParameters,"implements":implemented}},createModuleSpecifier:function(token){return{type:Syntax.ModuleSpecifier,value:token.value,raw:source.slice(token.range[0],token.range[1])}},createExportSpecifier:function(id,name){return{type:Syntax.ExportSpecifier,id:id,name:name}},createExportBatchSpecifier:function(){return{type:Syntax.ExportBatchSpecifier}},createImportDefaultSpecifier:function(id){return{type:Syntax.ImportDefaultSpecifier,id:id}},createImportNamespaceSpecifier:function(id){return{type:Syntax.ImportNamespaceSpecifier,id:id}},createExportDeclaration:function(isDefault,declaration,specifiers,source){return{type:Syntax.ExportDeclaration,"default":!!isDefault,declaration:declaration,specifiers:specifiers,source:source}},createImportSpecifier:function(id,name){return{type:Syntax.ImportSpecifier,id:id,name:name}},createImportDeclaration:function(specifiers,source){return{type:Syntax.ImportDeclaration,specifiers:specifiers,source:source}},createYieldExpression:function(argument,delegate){return{type:Syntax.YieldExpression,argument:argument,delegate:delegate}},createAwaitExpression:function(argument){return{type:Syntax.AwaitExpression,argument:argument}},createComprehensionExpression:function(filter,blocks,body){return{type:Syntax.ComprehensionExpression,filter:filter,blocks:blocks,body:body}}};function peekLineTerminator(){var pos,line,start,found;pos=index;line=lineNumber;start=lineStart;skipComment();found=lineNumber!==line;index=pos;lineNumber=line;lineStart=start;return found}function throwError(token,messageFormat){var error,args=Array.prototype.slice.call(arguments,2),msg=messageFormat.replace(/%(\d)/g,function(whole,index){assert(index<args.length,"Message reference must be in range");return args[index]});if(typeof token.lineNumber==="number"){error=new Error("Line "+token.lineNumber+": "+msg);error.index=token.range[0];error.lineNumber=token.lineNumber;error.column=token.range[0]-lineStart+1}else{error=new Error("Line "+lineNumber+": "+msg);error.index=index;error.lineNumber=lineNumber;error.column=index-lineStart+1}error.description=msg;throw error}function throwErrorTolerant(){try{throwError.apply(null,arguments)}catch(e){if(extra.errors){extra.errors.push(e)}else{throw e}}}function throwUnexpected(token){if(token.type===Token.EOF){throwError(token,Messages.UnexpectedEOS)}if(token.type===Token.NumericLiteral){throwError(token,Messages.UnexpectedNumber)}if(token.type===Token.StringLiteral||token.type===Token.XJSText){throwError(token,Messages.UnexpectedString)}if(token.type===Token.Identifier){throwError(token,Messages.UnexpectedIdentifier)}if(token.type===Token.Keyword){if(isFutureReservedWord(token.value)){throwError(token,Messages.UnexpectedReserved)}else if(strict&&isStrictModeReservedWord(token.value)){throwErrorTolerant(token,Messages.StrictReservedWord);return}throwError(token,Messages.UnexpectedToken,token.value)}if(token.type===Token.Template){throwError(token,Messages.UnexpectedTemplate,token.value.raw)}throwError(token,Messages.UnexpectedToken,token.value)}function expect(value){var token=lex();if(token.type!==Token.Punctuator||token.value!==value){throwUnexpected(token)
}}function expectKeyword(keyword,contextual){var token=lex();if(token.type!==(contextual?Token.Identifier:Token.Keyword)||token.value!==keyword){throwUnexpected(token)}}function expectContextualKeyword(keyword){return expectKeyword(keyword,true)}function match(value){return lookahead.type===Token.Punctuator&&lookahead.value===value}function matchKeyword(keyword,contextual){var expectedType=contextual?Token.Identifier:Token.Keyword;return lookahead.type===expectedType&&lookahead.value===keyword}function matchContextualKeyword(keyword){return matchKeyword(keyword,true)}function matchAssign(){var op;if(lookahead.type!==Token.Punctuator){return false}op=lookahead.value;return op==="="||op==="*="||op==="/="||op==="%="||op==="+="||op==="-="||op==="<<="||op===">>="||op===">>>="||op==="&="||op==="^="||op==="|="}function matchYield(){return state.yieldAllowed&&matchKeyword("yield",!strict)}function matchAsync(){var backtrackToken=lookahead,matches=false;if(matchContextualKeyword("async")){lex();matches=!peekLineTerminator();rewind(backtrackToken)}return matches}function matchAwait(){return state.awaitAllowed&&matchContextualKeyword("await")}function consumeSemicolon(){var line,oldIndex=index,oldLineNumber=lineNumber,oldLineStart=lineStart,oldLookahead=lookahead;if(source.charCodeAt(index)===59){lex();return}line=lineNumber;skipComment();if(lineNumber!==line){index=oldIndex;lineNumber=oldLineNumber;lineStart=oldLineStart;lookahead=oldLookahead;return}if(match(";")){lex();return}if(lookahead.type!==Token.EOF&&!match("}")){throwUnexpected(lookahead)}}function isLeftHandSide(expr){return expr.type===Syntax.Identifier||expr.type===Syntax.MemberExpression}function isAssignableLeftHandSide(expr){return isLeftHandSide(expr)||expr.type===Syntax.ObjectPattern||expr.type===Syntax.ArrayPattern}function parseArrayInitialiser(){var elements=[],blocks=[],filter=null,tmp,possiblecomprehension=true,body,marker=markerCreate();expect("[");while(!match("]")){if(lookahead.value==="for"&&lookahead.type===Token.Keyword){if(!possiblecomprehension){throwError({},Messages.ComprehensionError)}matchKeyword("for");tmp=parseForStatement({ignoreBody:true});tmp.of=tmp.type===Syntax.ForOfStatement;tmp.type=Syntax.ComprehensionBlock;if(tmp.left.kind){throwError({},Messages.ComprehensionError)}blocks.push(tmp)}else if(lookahead.value==="if"&&lookahead.type===Token.Keyword){if(!possiblecomprehension){throwError({},Messages.ComprehensionError)}expectKeyword("if");expect("(");filter=parseExpression();expect(")")}else if(lookahead.value===","&&lookahead.type===Token.Punctuator){possiblecomprehension=false;lex();elements.push(null)}else{tmp=parseSpreadOrAssignmentExpression();elements.push(tmp);if(tmp&&tmp.type===Syntax.SpreadElement){if(!match("]")){throwError({},Messages.ElementAfterSpreadElement)}}else if(!(match("]")||matchKeyword("for")||matchKeyword("if"))){expect(",");possiblecomprehension=false}}}expect("]");if(filter&&!blocks.length){throwError({},Messages.ComprehensionRequiresBlock)}if(blocks.length){if(elements.length!==1){throwError({},Messages.ComprehensionError)}return markerApply(marker,delegate.createComprehensionExpression(filter,blocks,elements[0]))}return markerApply(marker,delegate.createArrayExpression(elements))}function parsePropertyFunction(options){var previousStrict,previousYieldAllowed,previousAwaitAllowed,params,defaults,body,marker=markerCreate();previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=options.generator;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=options.async;params=options.params||[];defaults=options.defaults||[];body=parseConciseBody();if(options.name&&strict&&isRestrictedWord(params[0].name)){throwErrorTolerant(options.name,Messages.StrictParamName)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createFunctionExpression(null,params,defaults,body,options.rest||null,options.generator,body.type!==Syntax.BlockStatement,options.async,options.returnType,options.typeParameters))}function parsePropertyMethodFunction(options){var previousStrict,tmp,method;previousStrict=strict;strict=true;tmp=parseParams();if(tmp.stricted){throwErrorTolerant(tmp.stricted,tmp.message)}method=parsePropertyFunction({params:tmp.params,defaults:tmp.defaults,rest:tmp.rest,generator:options.generator,async:options.async,returnType:tmp.returnType,typeParameters:options.typeParameters});strict=previousStrict;return method}function parseObjectPropertyKey(){var marker=markerCreate(),token=lex(),propertyKey,result;if(token.type===Token.StringLiteral||token.type===Token.NumericLiteral){if(strict&&token.octal){throwErrorTolerant(token,Messages.StrictOctalLiteral)}return markerApply(marker,delegate.createLiteral(token))}if(token.type===Token.Punctuator&&token.value==="["){marker=markerCreate();propertyKey=parseAssignmentExpression();result=markerApply(marker,propertyKey);expect("]");return result}return markerApply(marker,delegate.createIdentifier(token.value))}function parseObjectProperty(){var token,key,id,value,param,expr,computed,marker=markerCreate(),returnType;token=lookahead;computed=token.value==="[";if(token.type===Token.Identifier||computed||matchAsync()){id=parseObjectPropertyKey();if(match(":")){lex();return markerApply(marker,delegate.createProperty("init",id,parseAssignmentExpression(),false,false,computed))}if(match("(")){return markerApply(marker,delegate.createProperty("init",id,parsePropertyMethodFunction({generator:false,async:false}),true,false,computed))}if(token.value==="get"){computed=lookahead.value==="[";key=parseObjectPropertyKey();expect("(");expect(")");if(match(":")){returnType=parseTypeAnnotation()}return markerApply(marker,delegate.createProperty("get",key,parsePropertyFunction({generator:false,async:false,returnType:returnType}),false,false,computed))}if(token.value==="set"){computed=lookahead.value==="[";key=parseObjectPropertyKey();expect("(");token=lookahead;param=[parseTypeAnnotatableIdentifier()];expect(")");if(match(":")){returnType=parseTypeAnnotation()}return markerApply(marker,delegate.createProperty("set",key,parsePropertyFunction({params:param,generator:false,async:false,name:token,returnType:returnType}),false,false,computed))}if(token.value==="async"){computed=lookahead.value==="[";key=parseObjectPropertyKey();return markerApply(marker,delegate.createProperty("init",key,parsePropertyMethodFunction({generator:false,async:true}),true,false,computed))}if(computed){throwUnexpected(lookahead)}return markerApply(marker,delegate.createProperty("init",id,id,false,true,false))}if(token.type===Token.EOF||token.type===Token.Punctuator){if(!match("*")){throwUnexpected(token)}lex();computed=lookahead.type===Token.Punctuator&&lookahead.value==="[";id=parseObjectPropertyKey();if(!match("(")){throwUnexpected(lex())}return markerApply(marker,delegate.createProperty("init",id,parsePropertyMethodFunction({generator:true}),true,false,computed))}key=parseObjectPropertyKey();if(match(":")){lex();return markerApply(marker,delegate.createProperty("init",key,parseAssignmentExpression(),false,false,false))}if(match("(")){return markerApply(marker,delegate.createProperty("init",key,parsePropertyMethodFunction({generator:false}),true,false,false))}throwUnexpected(lex())}function parseObjectSpreadProperty(){var marker=markerCreate();expect("...");return markerApply(marker,delegate.createSpreadProperty(parseAssignmentExpression()))}function parseObjectInitialiser(){var properties=[],property,name,key,kind,map={},toString=String,marker=markerCreate();expect("{");while(!match("}")){if(match("...")){property=parseObjectSpreadProperty()}else{property=parseObjectProperty();if(property.key.type===Syntax.Identifier){name=property.key.name}else{name=toString(property.key.value)}kind=property.kind==="init"?PropertyKind.Data:property.kind==="get"?PropertyKind.Get:PropertyKind.Set;key="$"+name;if(Object.prototype.hasOwnProperty.call(map,key)){if(map[key]===PropertyKind.Data){if(strict&&kind===PropertyKind.Data){throwErrorTolerant({},Messages.StrictDuplicateProperty)}else if(kind!==PropertyKind.Data){throwErrorTolerant({},Messages.AccessorDataProperty)}}else{if(kind===PropertyKind.Data){throwErrorTolerant({},Messages.AccessorDataProperty)}else if(map[key]&kind){throwErrorTolerant({},Messages.AccessorGetSet)}}map[key]|=kind}else{map[key]=kind}}properties.push(property);if(!match("}")){expect(",")}}expect("}");return markerApply(marker,delegate.createObjectExpression(properties))}function parseTemplateElement(option){var marker=markerCreate(),token=scanTemplateElement(option);if(strict&&token.octal){throwError(token,Messages.StrictOctalLiteral)}return markerApply(marker,delegate.createTemplateElement({raw:token.value.raw,cooked:token.value.cooked},token.tail))}function parseTemplateLiteral(){var quasi,quasis,expressions,marker=markerCreate();quasi=parseTemplateElement({head:true});quasis=[quasi];expressions=[];while(!quasi.tail){expressions.push(parseExpression());quasi=parseTemplateElement({head:false});quasis.push(quasi)}return markerApply(marker,delegate.createTemplateLiteral(quasis,expressions))}function parseGroupExpression(){var expr;expect("(");++state.parenthesizedCount;expr=parseExpression();expect(")");return expr}function matchAsyncFuncExprOrDecl(){var token;if(matchAsync()){token=lookahead2();if(token.type===Token.Keyword&&token.value==="function"){return true}}return false}function parsePrimaryExpression(){var marker,type,token,expr;type=lookahead.type;if(type===Token.Identifier){marker=markerCreate();return markerApply(marker,delegate.createIdentifier(lex().value))}if(type===Token.StringLiteral||type===Token.NumericLiteral){if(strict&&lookahead.octal){throwErrorTolerant(lookahead,Messages.StrictOctalLiteral)}marker=markerCreate();return markerApply(marker,delegate.createLiteral(lex()))}if(type===Token.Keyword){if(matchKeyword("this")){marker=markerCreate();lex();return markerApply(marker,delegate.createThisExpression())}if(matchKeyword("function")){return parseFunctionExpression()}if(matchKeyword("class")){return parseClassExpression()}if(matchKeyword("super")){marker=markerCreate();lex();return markerApply(marker,delegate.createIdentifier("super"))}}if(type===Token.BooleanLiteral){marker=markerCreate();token=lex();token.value=token.value==="true";return markerApply(marker,delegate.createLiteral(token))}if(type===Token.NullLiteral){marker=markerCreate();token=lex();token.value=null;return markerApply(marker,delegate.createLiteral(token))}if(match("[")){return parseArrayInitialiser()}if(match("{")){return parseObjectInitialiser()}if(match("(")){return parseGroupExpression()}if(match("/")||match("/=")){marker=markerCreate();return markerApply(marker,delegate.createLiteral(scanRegExp()))}if(type===Token.Template){return parseTemplateLiteral()}if(match("<")){return parseXJSElement()}throwUnexpected(lex())}function parseArguments(){var args=[],arg;expect("(");if(!match(")")){while(index<length){arg=parseSpreadOrAssignmentExpression();args.push(arg);if(match(")")){break}else if(arg.type===Syntax.SpreadElement){throwError({},Messages.ElementAfterSpreadElement)}expect(",")}}expect(")");return args}function parseSpreadOrAssignmentExpression(){if(match("...")){var marker=markerCreate();lex();return markerApply(marker,delegate.createSpreadElement(parseAssignmentExpression()))}return parseAssignmentExpression()}function parseNonComputedProperty(){var marker=markerCreate(),token=lex();if(!isIdentifierName(token)){throwUnexpected(token)}return markerApply(marker,delegate.createIdentifier(token.value))}function parseNonComputedMember(){expect(".");return parseNonComputedProperty()}function parseComputedMember(){var expr;expect("[");expr=parseExpression();expect("]");return expr}function parseNewExpression(){var callee,args,marker=markerCreate();expectKeyword("new");callee=parseLeftHandSideExpression();args=match("(")?parseArguments():[];return markerApply(marker,delegate.createNewExpression(callee,args))}function parseLeftHandSideExpressionAllowCall(){var expr,args,marker=markerCreate();expr=matchKeyword("new")?parseNewExpression():parsePrimaryExpression();while(match(".")||match("[")||match("(")||lookahead.type===Token.Template){if(match("(")){args=parseArguments();expr=markerApply(marker,delegate.createCallExpression(expr,args))}else if(match("[")){expr=markerApply(marker,delegate.createMemberExpression("[",expr,parseComputedMember()))}else if(match(".")){expr=markerApply(marker,delegate.createMemberExpression(".",expr,parseNonComputedMember()))}else{expr=markerApply(marker,delegate.createTaggedTemplateExpression(expr,parseTemplateLiteral()))}}return expr}function parseLeftHandSideExpression(){var expr,marker=markerCreate();expr=matchKeyword("new")?parseNewExpression():parsePrimaryExpression();while(match(".")||match("[")||lookahead.type===Token.Template){if(match("[")){expr=markerApply(marker,delegate.createMemberExpression("[",expr,parseComputedMember()))}else if(match(".")){expr=markerApply(marker,delegate.createMemberExpression(".",expr,parseNonComputedMember()))}else{expr=markerApply(marker,delegate.createTaggedTemplateExpression(expr,parseTemplateLiteral()))}}return expr}function parsePostfixExpression(){var marker=markerCreate(),expr=parseLeftHandSideExpressionAllowCall(),token;if(lookahead.type!==Token.Punctuator){return expr}if((match("++")||match("--"))&&!peekLineTerminator()){if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){throwErrorTolerant({},Messages.StrictLHSPostfix)}if(!isLeftHandSide(expr)){throwError({},Messages.InvalidLHSInAssignment)}token=lex();expr=markerApply(marker,delegate.createPostfixExpression(token.value,expr))}return expr}function parseUnaryExpression(){var marker,token,expr;if(lookahead.type!==Token.Punctuator&&lookahead.type!==Token.Keyword){return parsePostfixExpression()}if(match("++")||match("--")){marker=markerCreate();token=lex();expr=parseUnaryExpression();if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){throwErrorTolerant({},Messages.StrictLHSPrefix)}if(!isLeftHandSide(expr)){throwError({},Messages.InvalidLHSInAssignment)}return markerApply(marker,delegate.createUnaryExpression(token.value,expr))}if(match("+")||match("-")||match("~")||match("!")){marker=markerCreate();token=lex();expr=parseUnaryExpression();return markerApply(marker,delegate.createUnaryExpression(token.value,expr))}if(matchKeyword("delete")||matchKeyword("void")||matchKeyword("typeof")){marker=markerCreate();token=lex();expr=parseUnaryExpression();expr=markerApply(marker,delegate.createUnaryExpression(token.value,expr));if(strict&&expr.operator==="delete"&&expr.argument.type===Syntax.Identifier){throwErrorTolerant({},Messages.StrictDelete)}return expr}return parsePostfixExpression()}function binaryPrecedence(token,allowIn){var prec=0;if(token.type!==Token.Punctuator&&token.type!==Token.Keyword){return 0}switch(token.value){case"||":prec=1;break;case"&&":prec=2;break;case"|":prec=3;break;case"^":prec=4;break;case"&":prec=5;break;case"==":case"!=":case"===":case"!==":prec=6;break;case"<":case">":case"<=":case">=":case"instanceof":prec=7;break;case"in":prec=allowIn?7:0;break;case"<<":case">>":case">>>":prec=8;break;case"+":case"-":prec=9;break;case"*":case"/":case"%":prec=11;break;default:break}return prec}function parseBinaryExpression(){var expr,token,prec,previousAllowIn,stack,right,operator,left,i,marker,markers;previousAllowIn=state.allowIn;state.allowIn=true;marker=markerCreate();left=parseUnaryExpression();token=lookahead;prec=binaryPrecedence(token,previousAllowIn);if(prec===0){return left}token.prec=prec;lex();markers=[marker,markerCreate()];right=parseUnaryExpression();stack=[left,token,right];while((prec=binaryPrecedence(lookahead,previousAllowIn))>0){while(stack.length>2&&prec<=stack[stack.length-2].prec){right=stack.pop();operator=stack.pop().value;left=stack.pop();expr=delegate.createBinaryExpression(operator,left,right);markers.pop();marker=markers.pop();markerApply(marker,expr);stack.push(expr);markers.push(marker)}token=lex();token.prec=prec;stack.push(token);markers.push(markerCreate());expr=parseUnaryExpression();stack.push(expr)}state.allowIn=previousAllowIn;i=stack.length-1;expr=stack[i];markers.pop();while(i>1){expr=delegate.createBinaryExpression(stack[i-1].value,stack[i-2],expr);i-=2;marker=markers.pop();markerApply(marker,expr)}return expr}function parseConditionalExpression(){var expr,previousAllowIn,consequent,alternate,marker=markerCreate();expr=parseBinaryExpression();if(match("?")){lex();previousAllowIn=state.allowIn;state.allowIn=true;consequent=parseAssignmentExpression();state.allowIn=previousAllowIn;expect(":");alternate=parseAssignmentExpression();expr=markerApply(marker,delegate.createConditionalExpression(expr,consequent,alternate))}return expr}function reinterpretAsAssignmentBindingPattern(expr){var i,len,property,element;if(expr.type===Syntax.ObjectExpression){expr.type=Syntax.ObjectPattern;for(i=0,len=expr.properties.length;i<len;i+=1){property=expr.properties[i];if(property.type===Syntax.SpreadProperty){if(i<len-1){throwError({},Messages.PropertyAfterSpreadProperty)}reinterpretAsAssignmentBindingPattern(property.argument)}else{if(property.kind!=="init"){throwError({},Messages.InvalidLHSInAssignment)}reinterpretAsAssignmentBindingPattern(property.value)}}}else if(expr.type===Syntax.ArrayExpression){expr.type=Syntax.ArrayPattern;for(i=0,len=expr.elements.length;i<len;i+=1){element=expr.elements[i];if(element){reinterpretAsAssignmentBindingPattern(element)}}}else if(expr.type===Syntax.Identifier){if(isRestrictedWord(expr.name)){throwError({},Messages.InvalidLHSInAssignment)}}else if(expr.type===Syntax.SpreadElement){reinterpretAsAssignmentBindingPattern(expr.argument);if(expr.argument.type===Syntax.ObjectPattern){throwError({},Messages.ObjectPatternAsSpread)}}else{if(expr.type!==Syntax.MemberExpression&&expr.type!==Syntax.CallExpression&&expr.type!==Syntax.NewExpression){throwError({},Messages.InvalidLHSInAssignment)}}}function reinterpretAsDestructuredParameter(options,expr){var i,len,property,element;if(expr.type===Syntax.ObjectExpression){expr.type=Syntax.ObjectPattern;for(i=0,len=expr.properties.length;i<len;i+=1){property=expr.properties[i];if(property.type===Syntax.SpreadProperty){if(i<len-1){throwError({},Messages.PropertyAfterSpreadProperty)}reinterpretAsDestructuredParameter(options,property.argument)}else{if(property.kind!=="init"){throwError({},Messages.InvalidLHSInFormalsList)}reinterpretAsDestructuredParameter(options,property.value)}}}else if(expr.type===Syntax.ArrayExpression){expr.type=Syntax.ArrayPattern;for(i=0,len=expr.elements.length;i<len;i+=1){element=expr.elements[i];if(element){reinterpretAsDestructuredParameter(options,element)}}}else if(expr.type===Syntax.Identifier){validateParam(options,expr,expr.name)}else{if(expr.type!==Syntax.MemberExpression){throwError({},Messages.InvalidLHSInFormalsList)}}}function reinterpretAsCoverFormalsList(expressions){var i,len,param,params,defaults,defaultCount,options,rest;params=[];defaults=[];defaultCount=0;rest=null;options={paramSet:{}};for(i=0,len=expressions.length;i<len;i+=1){param=expressions[i];if(param.type===Syntax.Identifier){params.push(param);defaults.push(null);validateParam(options,param,param.name)}else if(param.type===Syntax.ObjectExpression||param.type===Syntax.ArrayExpression){reinterpretAsDestructuredParameter(options,param);params.push(param);defaults.push(null)}else if(param.type===Syntax.SpreadElement){assert(i===len-1,"It is guaranteed that SpreadElement is last element by parseExpression");reinterpretAsDestructuredParameter(options,param.argument);rest=param.argument}else if(param.type===Syntax.AssignmentExpression){params.push(param.left);defaults.push(param.right);++defaultCount;validateParam(options,param.left,param.left.name)}else{return null}}if(options.message===Messages.StrictParamDupe){throwError(strict?options.stricted:options.firstRestricted,options.message)}if(defaultCount===0){defaults=[]}return{params:params,defaults:defaults,rest:rest,stricted:options.stricted,firstRestricted:options.firstRestricted,message:options.message}}function parseArrowFunctionExpression(options,marker){var previousStrict,previousYieldAllowed,previousAwaitAllowed,body;expect("=>");previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=false;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=!!options.async;body=parseConciseBody();if(strict&&options.firstRestricted){throwError(options.firstRestricted,options.message)}if(strict&&options.stricted){throwErrorTolerant(options.stricted,options.message)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createArrowFunctionExpression(options.params,options.defaults,body,options.rest,body.type!==Syntax.BlockStatement,!!options.async))}function parseAssignmentExpression(){var marker,expr,token,params,oldParenthesizedCount,backtrackToken=lookahead,possiblyAsync=false;if(matchYield()){return parseYieldExpression()}if(matchAwait()){return parseAwaitExpression()}oldParenthesizedCount=state.parenthesizedCount;marker=markerCreate();if(matchAsyncFuncExprOrDecl()){return parseFunctionExpression()}if(matchAsync()){possiblyAsync=true;lex()}if(match("(")){token=lookahead2();if(token.type===Token.Punctuator&&token.value===")"||token.value==="..."){params=parseParams();if(!match("=>")){throwUnexpected(lex())}params.async=possiblyAsync;return parseArrowFunctionExpression(params,marker)}}token=lookahead;if(possiblyAsync&&!match("(")&&token.type!==Token.Identifier){possiblyAsync=false;rewind(backtrackToken)}expr=parseConditionalExpression();if(match("=>")&&(state.parenthesizedCount===oldParenthesizedCount||state.parenthesizedCount===oldParenthesizedCount+1)){if(expr.type===Syntax.Identifier){params=reinterpretAsCoverFormalsList([expr])}else if(expr.type===Syntax.SequenceExpression){params=reinterpretAsCoverFormalsList(expr.expressions)}if(params){params.async=possiblyAsync;return parseArrowFunctionExpression(params,marker)}}if(possiblyAsync){possiblyAsync=false;rewind(backtrackToken);expr=parseConditionalExpression()}if(matchAssign()){if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){throwErrorTolerant(token,Messages.StrictLHSAssignment)}if(match("=")&&(expr.type===Syntax.ObjectExpression||expr.type===Syntax.ArrayExpression)){reinterpretAsAssignmentBindingPattern(expr)}else if(!isLeftHandSide(expr)){throwError({},Messages.InvalidLHSInAssignment)}expr=markerApply(marker,delegate.createAssignmentExpression(lex().value,expr,parseAssignmentExpression()))}return expr}function parseExpression(){var marker,expr,expressions,sequence,coverFormalsList,spreadFound,oldParenthesizedCount;oldParenthesizedCount=state.parenthesizedCount;marker=markerCreate();expr=parseAssignmentExpression();expressions=[expr];if(match(",")){while(index<length){if(!match(",")){break}lex();expr=parseSpreadOrAssignmentExpression();expressions.push(expr);if(expr.type===Syntax.SpreadElement){spreadFound=true;if(!match(")")){throwError({},Messages.ElementAfterSpreadElement)}break}}sequence=markerApply(marker,delegate.createSequenceExpression(expressions))}if(match("=>")){if(state.parenthesizedCount===oldParenthesizedCount||state.parenthesizedCount===oldParenthesizedCount+1){expr=expr.type===Syntax.SequenceExpression?expr.expressions:expressions;coverFormalsList=reinterpretAsCoverFormalsList(expr);if(coverFormalsList){return parseArrowFunctionExpression(coverFormalsList,marker)}}throwUnexpected(lex())}if(spreadFound&&lookahead2().value!=="=>"){throwError({},Messages.IllegalSpread)}return sequence||expr}function parseStatementList(){var list=[],statement;while(index<length){if(match("}")){break}statement=parseSourceElement();if(typeof statement==="undefined"){break}list.push(statement)}return list}function parseBlock(){var block,marker=markerCreate();expect("{");block=parseStatementList();expect("}");return markerApply(marker,delegate.createBlockStatement(block))}function parseTypeParameterDeclaration(){var marker=markerCreate(),paramTypes=[];expect("<");while(!match(">")){paramTypes.push(parseVariableIdentifier());if(!match(">")){expect(",")}}expect(">");return markerApply(marker,delegate.createTypeParameterDeclaration(paramTypes))}function parseTypeParameterInstantiation(){var marker=markerCreate(),oldInType=state.inType,paramTypes=[];state.inType=true;expect("<");while(!match(">")){paramTypes.push(parseType());if(!match(">")){expect(",")}}expect(">");state.inType=oldInType;return markerApply(marker,delegate.createTypeParameterInstantiation(paramTypes))}function parseObjectTypeIndexer(marker,isStatic){var id,key,value;expect("[");id=parseObjectPropertyKey();expect(":");key=parseType();expect("]");expect(":");value=parseType();return markerApply(marker,delegate.createObjectTypeIndexer(id,key,value,isStatic))}function parseObjectTypeMethodish(marker){var params=[],rest=null,returnType,typeParameters=null;if(match("<")){typeParameters=parseTypeParameterDeclaration()}expect("(");while(lookahead.type===Token.Identifier){params.push(parseFunctionTypeParam());if(!match(")")){expect(",")}}if(match("...")){lex();rest=parseFunctionTypeParam()}expect(")");expect(":");returnType=parseType();return markerApply(marker,delegate.createFunctionTypeAnnotation(params,returnType,rest,typeParameters))}function parseObjectTypeMethod(marker,isStatic,key){var optional=false,value;value=parseObjectTypeMethodish(marker);return markerApply(marker,delegate.createObjectTypeProperty(key,value,optional,isStatic))}function parseObjectTypeCallProperty(marker,isStatic){var valueMarker=markerCreate();return markerApply(marker,delegate.createObjectTypeCallProperty(parseObjectTypeMethodish(valueMarker),isStatic))}function parseObjectType(allowStatic){var callProperties=[],indexers=[],marker,optional=false,properties=[],property,propertyKey,propertyTypeAnnotation,token,isStatic;expect("{");while(!match("}")){marker=markerCreate();if(allowStatic&&matchContextualKeyword("static")){token=lex();isStatic=true}if(match("[")){indexers.push(parseObjectTypeIndexer(marker,isStatic))}else if(match("(")||match("<")){callProperties.push(parseObjectTypeCallProperty(marker,allowStatic))}else{if(isStatic&&match(":")){propertyKey=markerApply(marker,delegate.createIdentifier(token));throwErrorTolerant(token,Messages.StrictReservedWord)}else{propertyKey=parseObjectPropertyKey()}if(match("<")||match("(")){properties.push(parseObjectTypeMethod(marker,isStatic,propertyKey))}else{if(match("?")){lex();optional=true}expect(":");propertyTypeAnnotation=parseType();properties.push(markerApply(marker,delegate.createObjectTypeProperty(propertyKey,propertyTypeAnnotation,optional,isStatic)))}}if(match(";")){lex()}else if(!match("}")){throwUnexpected(lookahead)}}expect("}");return delegate.createObjectTypeAnnotation(properties,indexers,callProperties)}function parseGenericType(){var marker=markerCreate(),returnType=null,typeParameters=null,typeIdentifier,typeIdentifierMarker=markerCreate;typeIdentifier=parseVariableIdentifier();while(match(".")){expect(".");typeIdentifier=markerApply(marker,delegate.createQualifiedTypeIdentifier(typeIdentifier,parseVariableIdentifier()))}if(match("<")){typeParameters=parseTypeParameterInstantiation()}return markerApply(marker,delegate.createGenericTypeAnnotation(typeIdentifier,typeParameters))}function parseVoidType(){var marker=markerCreate();expectKeyword("void");return markerApply(marker,delegate.createVoidTypeAnnotation())}function parseTypeofType(){var argument,marker=markerCreate();expectKeyword("typeof");argument=parsePrimaryType();return markerApply(marker,delegate.createTypeofTypeAnnotation(argument))}function parseTupleType(){var marker=markerCreate(),types=[];expect("[");while(index<length&&!match("]")){types.push(parseType());if(match("]")){break}expect(",")}expect("]");return markerApply(marker,delegate.createTupleTypeAnnotation(types))}function parseFunctionTypeParam(){var marker=markerCreate(),name,optional=false,typeAnnotation;name=parseVariableIdentifier();if(match("?")){lex();optional=true}expect(":");typeAnnotation=parseType();return markerApply(marker,delegate.createFunctionTypeParam(name,typeAnnotation,optional))}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(lookahead.type===Token.Identifier){ret.params.push(parseFunctionTypeParam());if(!match(")")){expect(",")}}if(match("...")){lex();ret.rest=parseFunctionTypeParam()}return ret}function parsePrimaryType(){var typeIdentifier=null,params=null,returnType=null,marker=markerCreate(),rest=null,tmp,typeParameters,token,type,isGroupedType=false;switch(lookahead.type){case Token.Identifier:switch(lookahead.value){case"any":lex();return markerApply(marker,delegate.createAnyTypeAnnotation());case"bool":case"boolean":lex();return markerApply(marker,delegate.createBooleanTypeAnnotation());case"number":lex();return markerApply(marker,delegate.createNumberTypeAnnotation());case"string":lex();return markerApply(marker,delegate.createStringTypeAnnotation())}return markerApply(marker,parseGenericType());case Token.Punctuator:switch(lookahead.value){case"{":return markerApply(marker,parseObjectType());case"[":return parseTupleType();case"<":typeParameters=parseTypeParameterDeclaration();expect("(");tmp=parseFunctionTypeParams();params=tmp.params;rest=tmp.rest;expect(")");expect("=>");returnType=parseType();return markerApply(marker,delegate.createFunctionTypeAnnotation(params,returnType,rest,typeParameters));case"(":lex();if(!match(")")&&!match("...")){if(lookahead.type===Token.Identifier){token=lookahead2();isGroupedType=token.value!=="?"&&token.value!==":"}else{isGroupedType=true}}if(isGroupedType){type=parseType();expect(")");if(match("=>")){throwError({},Messages.ConfusedAboutFunctionType)}return type}tmp=parseFunctionTypeParams();params=tmp.params;rest=tmp.rest;expect(")");expect("=>");returnType=parseType();return markerApply(marker,delegate.createFunctionTypeAnnotation(params,returnType,rest,null))}break;case Token.Keyword:switch(lookahead.value){case"void":return markerApply(marker,parseVoidType());case"typeof":return markerApply(marker,parseTypeofType())}break;case Token.StringLiteral:token=lex();if(token.octal){throwError(token,Messages.StrictOctalLiteral)}return markerApply(marker,delegate.createStringLiteralTypeAnnotation(token))}throwUnexpected(lookahead)}function parsePostfixType(){var marker=markerCreate(),t=parsePrimaryType();if(match("[")){expect("[");expect("]");return markerApply(marker,delegate.createArrayTypeAnnotation(t))}return t}function parsePrefixType(){var marker=markerCreate();if(match("?")){lex();return markerApply(marker,delegate.createNullableTypeAnnotation(parsePrefixType()))}return parsePostfixType()}function parseIntersectionType(){var marker=markerCreate(),type,types;type=parsePrefixType();types=[type];while(match("&")){lex();types.push(parsePrefixType())}return types.length===1?type:markerApply(marker,delegate.createIntersectionTypeAnnotation(types))}function parseUnionType(){var marker=markerCreate(),type,types;type=parseIntersectionType();types=[type];while(match("|")){lex();types.push(parseIntersectionType())}return types.length===1?type:markerApply(marker,delegate.createUnionTypeAnnotation(types))}function parseType(){var oldInType=state.inType,type;state.inType=true;type=parseUnionType();state.inType=oldInType;return type}function parseTypeAnnotation(){var marker=markerCreate(),type;expect(":");type=parseType();return markerApply(marker,delegate.createTypeAnnotation(type))}function parseVariableIdentifier(){var marker=markerCreate(),token=lex();if(token.type!==Token.Identifier){throwUnexpected(token)}return markerApply(marker,delegate.createIdentifier(token.value))}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var marker=markerCreate(),ident=parseVariableIdentifier(),isOptionalParam=false;if(canBeOptionalParam&&match("?")){expect("?");
isOptionalParam=true}if(requireTypeAnnotation||match(":")){ident.typeAnnotation=parseTypeAnnotation();ident=markerApply(marker,ident)}if(isOptionalParam){ident.optional=true;ident=markerApply(marker,ident)}return ident}function parseVariableDeclaration(kind){var id,marker=markerCreate(),init=null,typeAnnotationMarker=markerCreate();if(match("{")){id=parseObjectInitialiser();reinterpretAsAssignmentBindingPattern(id);if(match(":")){id.typeAnnotation=parseTypeAnnotation();markerApply(typeAnnotationMarker,id)}}else if(match("[")){id=parseArrayInitialiser();reinterpretAsAssignmentBindingPattern(id);if(match(":")){id.typeAnnotation=parseTypeAnnotation();markerApply(typeAnnotationMarker,id)}}else{id=state.allowKeyword?parseNonComputedProperty():parseTypeAnnotatableIdentifier();if(strict&&isRestrictedWord(id.name)){throwErrorTolerant({},Messages.StrictVarName)}}if(kind==="const"){if(!match("=")){throwError({},Messages.NoUnintializedConst)}expect("=");init=parseAssignmentExpression()}else if(match("=")){lex();init=parseAssignmentExpression()}return markerApply(marker,delegate.createVariableDeclarator(id,init))}function parseVariableDeclarationList(kind){var list=[];do{list.push(parseVariableDeclaration(kind));if(!match(",")){break}lex()}while(index<length);return list}function parseVariableStatement(){var declarations,marker=markerCreate();expectKeyword("var");declarations=parseVariableDeclarationList();consumeSemicolon();return markerApply(marker,delegate.createVariableDeclaration(declarations,"var"))}function parseConstLetDeclaration(kind){var declarations,marker=markerCreate();expectKeyword(kind);declarations=parseVariableDeclarationList(kind);consumeSemicolon();return markerApply(marker,delegate.createVariableDeclaration(declarations,kind))}function parseModuleSpecifier(){var marker=markerCreate(),specifier;if(lookahead.type!==Token.StringLiteral){throwError({},Messages.InvalidModuleSpecifier)}specifier=delegate.createModuleSpecifier(lookahead);lex();return markerApply(marker,specifier)}function parseExportBatchSpecifier(){var marker=markerCreate();expect("*");return markerApply(marker,delegate.createExportBatchSpecifier())}function parseExportSpecifier(){var id,name=null,marker=markerCreate(),from;if(matchKeyword("default")){lex();id=markerApply(marker,delegate.createIdentifier("default"))}else{id=parseVariableIdentifier()}if(matchContextualKeyword("as")){lex();name=parseNonComputedProperty()}return markerApply(marker,delegate.createExportSpecifier(id,name))}function parseExportDeclaration(){var backtrackToken,id,previousAllowKeyword,declaration=null,isExportFromIdentifier,src=null,specifiers=[],marker=markerCreate();expectKeyword("export");if(matchKeyword("default")){lex();if(matchKeyword("function")||matchKeyword("class")){backtrackToken=lookahead;lex();if(isIdentifierName(lookahead)){id=parseNonComputedProperty();rewind(backtrackToken);return markerApply(marker,delegate.createExportDeclaration(true,parseSourceElement(),[id],null))}rewind(backtrackToken);switch(lookahead.value){case"class":return markerApply(marker,delegate.createExportDeclaration(true,parseClassExpression(),[],null));case"function":return markerApply(marker,delegate.createExportDeclaration(true,parseFunctionExpression(),[],null))}}if(matchContextualKeyword("from")){throwError({},Messages.UnexpectedToken,lookahead.value)}if(match("{")){declaration=parseObjectInitialiser()}else if(match("[")){declaration=parseArrayInitialiser()}else{declaration=parseAssignmentExpression()}consumeSemicolon();return markerApply(marker,delegate.createExportDeclaration(true,declaration,[],null))}if(lookahead.type===Token.Keyword){switch(lookahead.value){case"let":case"const":case"var":case"class":case"function":return markerApply(marker,delegate.createExportDeclaration(false,parseSourceElement(),specifiers,null))}}if(match("*")){specifiers.push(parseExportBatchSpecifier());if(!matchContextualKeyword("from")){throwError({},lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value)}lex();src=parseModuleSpecifier();consumeSemicolon();return markerApply(marker,delegate.createExportDeclaration(false,null,specifiers,src))}expect("{");do{isExportFromIdentifier=isExportFromIdentifier||matchKeyword("default");specifiers.push(parseExportSpecifier())}while(match(",")&&lex());expect("}");if(matchContextualKeyword("from")){lex();src=parseModuleSpecifier();consumeSemicolon()}else if(isExportFromIdentifier){throwError({},lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value)}else{consumeSemicolon()}return markerApply(marker,delegate.createExportDeclaration(false,declaration,specifiers,src))}function parseImportSpecifier(){var id,name=null,marker=markerCreate();id=parseNonComputedProperty();if(matchContextualKeyword("as")){lex();name=parseVariableIdentifier()}return markerApply(marker,delegate.createImportSpecifier(id,name))}function parseNamedImports(){var specifiers=[];expect("{");do{specifiers.push(parseImportSpecifier())}while(match(",")&&lex());expect("}");return specifiers}function parseImportDefaultSpecifier(){var id,marker=markerCreate();id=parseNonComputedProperty();return markerApply(marker,delegate.createImportDefaultSpecifier(id))}function parseImportNamespaceSpecifier(){var id,marker=markerCreate();expect("*");if(!matchContextualKeyword("as")){throwError({},Messages.NoAsAfterImportNamespace)}lex();id=parseNonComputedProperty();return markerApply(marker,delegate.createImportNamespaceSpecifier(id))}function parseImportDeclaration(){var specifiers,src,marker=markerCreate();expectKeyword("import");specifiers=[];if(lookahead.type===Token.StringLiteral){src=parseModuleSpecifier();consumeSemicolon();return markerApply(marker,delegate.createImportDeclaration(specifiers,src))}if(!matchKeyword("default")&&isIdentifierName(lookahead)){specifiers.push(parseImportDefaultSpecifier());if(match(",")){lex()}}if(match("*")){specifiers.push(parseImportNamespaceSpecifier())}else if(match("{")){specifiers=specifiers.concat(parseNamedImports())}if(!matchContextualKeyword("from")){throwError({},lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value)}lex();src=parseModuleSpecifier();consumeSemicolon();return markerApply(marker,delegate.createImportDeclaration(specifiers,src))}function parseEmptyStatement(){var marker=markerCreate();expect(";");return markerApply(marker,delegate.createEmptyStatement())}function parseExpressionStatement(){var marker=markerCreate(),expr=parseExpression();consumeSemicolon();return markerApply(marker,delegate.createExpressionStatement(expr))}function parseIfStatement(){var test,consequent,alternate,marker=markerCreate();expectKeyword("if");expect("(");test=parseExpression();expect(")");consequent=parseStatement();if(matchKeyword("else")){lex();alternate=parseStatement()}else{alternate=null}return markerApply(marker,delegate.createIfStatement(test,consequent,alternate))}function parseDoWhileStatement(){var body,test,oldInIteration,marker=markerCreate();expectKeyword("do");oldInIteration=state.inIteration;state.inIteration=true;body=parseStatement();state.inIteration=oldInIteration;expectKeyword("while");expect("(");test=parseExpression();expect(")");if(match(";")){lex()}return markerApply(marker,delegate.createDoWhileStatement(body,test))}function parseWhileStatement(){var test,body,oldInIteration,marker=markerCreate();expectKeyword("while");expect("(");test=parseExpression();expect(")");oldInIteration=state.inIteration;state.inIteration=true;body=parseStatement();state.inIteration=oldInIteration;return markerApply(marker,delegate.createWhileStatement(test,body))}function parseForVariableDeclaration(){var marker=markerCreate(),token=lex(),declarations=parseVariableDeclarationList();return markerApply(marker,delegate.createVariableDeclaration(declarations,token.value))}function parseForStatement(opts){var init,test,update,left,right,body,operator,oldInIteration,marker=markerCreate();init=test=update=null;expectKeyword("for");if(matchContextualKeyword("each")){throwError({},Messages.EachNotAllowed)}expect("(");if(match(";")){lex()}else{if(matchKeyword("var")||matchKeyword("let")||matchKeyword("const")){state.allowIn=false;init=parseForVariableDeclaration();state.allowIn=true;if(init.declarations.length===1){if(matchKeyword("in")||matchContextualKeyword("of")){operator=lookahead;if(!((operator.value==="in"||init.kind!=="var")&&init.declarations[0].init)){lex();left=init;right=parseExpression();init=null}}}}else{state.allowIn=false;init=parseExpression();state.allowIn=true;if(matchContextualKeyword("of")){operator=lex();left=init;right=parseExpression();init=null}else if(matchKeyword("in")){if(!isAssignableLeftHandSide(init)){throwError({},Messages.InvalidLHSInForIn)}operator=lex();left=init;right=parseExpression();init=null}}if(typeof left==="undefined"){expect(";")}}if(typeof left==="undefined"){if(!match(";")){test=parseExpression()}expect(";");if(!match(")")){update=parseExpression()}}expect(")");oldInIteration=state.inIteration;state.inIteration=true;if(!(opts!==undefined&&opts.ignoreBody)){body=parseStatement()}state.inIteration=oldInIteration;if(typeof left==="undefined"){return markerApply(marker,delegate.createForStatement(init,test,update,body))}if(operator.value==="in"){return markerApply(marker,delegate.createForInStatement(left,right,body))}return markerApply(marker,delegate.createForOfStatement(left,right,body))}function parseContinueStatement(){var label=null,key,marker=markerCreate();expectKeyword("continue");if(source.charCodeAt(index)===59){lex();if(!state.inIteration){throwError({},Messages.IllegalContinue)}return markerApply(marker,delegate.createContinueStatement(null))}if(peekLineTerminator()){if(!state.inIteration){throwError({},Messages.IllegalContinue)}return markerApply(marker,delegate.createContinueStatement(null))}if(lookahead.type===Token.Identifier){label=parseVariableIdentifier();key="$"+label.name;if(!Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError({},Messages.UnknownLabel,label.name)}}consumeSemicolon();if(label===null&&!state.inIteration){throwError({},Messages.IllegalContinue)}return markerApply(marker,delegate.createContinueStatement(label))}function parseBreakStatement(){var label=null,key,marker=markerCreate();expectKeyword("break");if(source.charCodeAt(index)===59){lex();if(!(state.inIteration||state.inSwitch)){throwError({},Messages.IllegalBreak)}return markerApply(marker,delegate.createBreakStatement(null))}if(peekLineTerminator()){if(!(state.inIteration||state.inSwitch)){throwError({},Messages.IllegalBreak)}return markerApply(marker,delegate.createBreakStatement(null))}if(lookahead.type===Token.Identifier){label=parseVariableIdentifier();key="$"+label.name;if(!Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError({},Messages.UnknownLabel,label.name)}}consumeSemicolon();if(label===null&&!(state.inIteration||state.inSwitch)){throwError({},Messages.IllegalBreak)}return markerApply(marker,delegate.createBreakStatement(label))}function parseReturnStatement(){var argument=null,marker=markerCreate();expectKeyword("return");if(!state.inFunctionBody){throwErrorTolerant({},Messages.IllegalReturn)}if(source.charCodeAt(index)===32){if(isIdentifierStart(source.charCodeAt(index+1))){argument=parseExpression();consumeSemicolon();return markerApply(marker,delegate.createReturnStatement(argument))}}if(peekLineTerminator()){return markerApply(marker,delegate.createReturnStatement(null))}if(!match(";")){if(!match("}")&&lookahead.type!==Token.EOF){argument=parseExpression()}}consumeSemicolon();return markerApply(marker,delegate.createReturnStatement(argument))}function parseWithStatement(){var object,body,marker=markerCreate();if(strict){throwErrorTolerant({},Messages.StrictModeWith)}expectKeyword("with");expect("(");object=parseExpression();expect(")");body=parseStatement();return markerApply(marker,delegate.createWithStatement(object,body))}function parseSwitchCase(){var test,consequent=[],sourceElement,marker=markerCreate();if(matchKeyword("default")){lex();test=null}else{expectKeyword("case");test=parseExpression()}expect(":");while(index<length){if(match("}")||matchKeyword("default")||matchKeyword("case")){break}sourceElement=parseSourceElement();if(typeof sourceElement==="undefined"){break}consequent.push(sourceElement)}return markerApply(marker,delegate.createSwitchCase(test,consequent))}function parseSwitchStatement(){var discriminant,cases,clause,oldInSwitch,defaultFound,marker=markerCreate();expectKeyword("switch");expect("(");discriminant=parseExpression();expect(")");expect("{");cases=[];if(match("}")){lex();return markerApply(marker,delegate.createSwitchStatement(discriminant,cases))}oldInSwitch=state.inSwitch;state.inSwitch=true;defaultFound=false;while(index<length){if(match("}")){break}clause=parseSwitchCase();if(clause.test===null){if(defaultFound){throwError({},Messages.MultipleDefaultsInSwitch)}defaultFound=true}cases.push(clause)}state.inSwitch=oldInSwitch;expect("}");return markerApply(marker,delegate.createSwitchStatement(discriminant,cases))}function parseThrowStatement(){var argument,marker=markerCreate();expectKeyword("throw");if(peekLineTerminator()){throwError({},Messages.NewlineAfterThrow)}argument=parseExpression();consumeSemicolon();return markerApply(marker,delegate.createThrowStatement(argument))}function parseCatchClause(){var param,body,marker=markerCreate();expectKeyword("catch");expect("(");if(match(")")){throwUnexpected(lookahead)}param=parseExpression();if(strict&¶m.type===Syntax.Identifier&&isRestrictedWord(param.name)){throwErrorTolerant({},Messages.StrictCatchVariable)}expect(")");body=parseBlock();return markerApply(marker,delegate.createCatchClause(param,body))}function parseTryStatement(){var block,handlers=[],finalizer=null,marker=markerCreate();expectKeyword("try");block=parseBlock();if(matchKeyword("catch")){handlers.push(parseCatchClause())}if(matchKeyword("finally")){lex();finalizer=parseBlock()}if(handlers.length===0&&!finalizer){throwError({},Messages.NoCatchOrFinally)}return markerApply(marker,delegate.createTryStatement(block,[],handlers,finalizer))}function parseDebuggerStatement(){var marker=markerCreate();expectKeyword("debugger");consumeSemicolon();return markerApply(marker,delegate.createDebuggerStatement())}function parseStatement(){var type=lookahead.type,marker,expr,labeledBody,key;if(type===Token.EOF){throwUnexpected(lookahead)}if(type===Token.Punctuator){switch(lookahead.value){case";":return parseEmptyStatement();case"{":return parseBlock();case"(":return parseExpressionStatement();default:break}}if(type===Token.Keyword){switch(lookahead.value){case"break":return parseBreakStatement();case"continue":return parseContinueStatement();case"debugger":return parseDebuggerStatement();case"do":return parseDoWhileStatement();case"for":return parseForStatement();case"function":return parseFunctionDeclaration();case"class":return parseClassDeclaration();case"if":return parseIfStatement();case"return":return parseReturnStatement();case"switch":return parseSwitchStatement();case"throw":return parseThrowStatement();case"try":return parseTryStatement();case"var":return parseVariableStatement();case"while":return parseWhileStatement();case"with":return parseWithStatement();default:break}}if(matchAsyncFuncExprOrDecl()){return parseFunctionDeclaration()}marker=markerCreate();expr=parseExpression();if(expr.type===Syntax.Identifier&&match(":")){lex();key="$"+expr.name;if(Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError({},Messages.Redeclaration,"Label",expr.name)}state.labelSet[key]=true;labeledBody=parseStatement();delete state.labelSet[key];return markerApply(marker,delegate.createLabeledStatement(expr,labeledBody))}consumeSemicolon();return markerApply(marker,delegate.createExpressionStatement(expr))}function parseConciseBody(){if(match("{")){return parseFunctionSourceElements()}return parseAssignmentExpression()}function parseFunctionSourceElements(){var sourceElement,sourceElements=[],token,directive,firstRestricted,oldLabelSet,oldInIteration,oldInSwitch,oldInFunctionBody,oldParenthesizedCount,marker=markerCreate();expect("{");while(index<length){if(lookahead.type!==Token.StringLiteral){break}token=lookahead;sourceElement=parseSourceElement();sourceElements.push(sourceElement);if(sourceElement.expression.type!==Syntax.Literal){break}directive=source.slice(token.range[0]+1,token.range[1]-1);if(directive==="use strict"){strict=true;if(firstRestricted){throwErrorTolerant(firstRestricted,Messages.StrictOctalLiteral)}}else{if(!firstRestricted&&token.octal){firstRestricted=token}}}oldLabelSet=state.labelSet;oldInIteration=state.inIteration;oldInSwitch=state.inSwitch;oldInFunctionBody=state.inFunctionBody;oldParenthesizedCount=state.parenthesizedCount;state.labelSet={};state.inIteration=false;state.inSwitch=false;state.inFunctionBody=true;state.parenthesizedCount=0;while(index<length){if(match("}")){break}sourceElement=parseSourceElement();if(typeof sourceElement==="undefined"){break}sourceElements.push(sourceElement)}expect("}");state.labelSet=oldLabelSet;state.inIteration=oldInIteration;state.inSwitch=oldInSwitch;state.inFunctionBody=oldInFunctionBody;state.parenthesizedCount=oldParenthesizedCount;return markerApply(marker,delegate.createBlockStatement(sourceElements))}function validateParam(options,param,name){var key="$"+name;if(strict){if(isRestrictedWord(name)){options.stricted=param;options.message=Messages.StrictParamName}if(Object.prototype.hasOwnProperty.call(options.paramSet,key)){options.stricted=param;options.message=Messages.StrictParamDupe}}else if(!options.firstRestricted){if(isRestrictedWord(name)){options.firstRestricted=param;options.message=Messages.StrictParamName}else if(isStrictModeReservedWord(name)){options.firstRestricted=param;options.message=Messages.StrictReservedWord}else if(Object.prototype.hasOwnProperty.call(options.paramSet,key)){options.firstRestricted=param;options.message=Messages.StrictParamDupe}}options.paramSet[key]=true}function parseParam(options){var marker,token,rest,param,def;token=lookahead;if(token.value==="..."){token=lex();rest=true}if(match("[")){marker=markerCreate();param=parseArrayInitialiser();reinterpretAsDestructuredParameter(options,param);if(match(":")){param.typeAnnotation=parseTypeAnnotation();markerApply(marker,param)}}else if(match("{")){marker=markerCreate();if(rest){throwError({},Messages.ObjectPatternAsRestParameter)}param=parseObjectInitialiser();reinterpretAsDestructuredParameter(options,param);if(match(":")){param.typeAnnotation=parseTypeAnnotation();markerApply(marker,param)}}else{param=rest?parseTypeAnnotatableIdentifier(false,false):parseTypeAnnotatableIdentifier(false,true);validateParam(options,token,token.value)}if(match("=")){if(rest){throwErrorTolerant(lookahead,Messages.DefaultRestParameter)}lex();def=parseAssignmentExpression();++options.defaultCount}if(rest){if(!match(")")){throwError({},Messages.ParameterAfterRestParameter)}options.rest=param;return false}options.params.push(param);options.defaults.push(def);return!match(")")}function parseParams(firstRestricted){var options,marker=markerCreate();options={params:[],defaultCount:0,defaults:[],rest:null,firstRestricted:firstRestricted};expect("(");if(!match(")")){options.paramSet={};while(index<length){if(!parseParam(options)){break}expect(",")}}expect(")");if(options.defaultCount===0){options.defaults=[]}if(match(":")){options.returnType=parseTypeAnnotation()}return markerApply(marker,options)}function parseFunctionDeclaration(){var id,body,token,tmp,firstRestricted,message,generator,isAsync,previousStrict,previousYieldAllowed,previousAwaitAllowed,marker=markerCreate(),typeParameters;isAsync=false;if(matchAsync()){lex();isAsync=true}expectKeyword("function");generator=false;if(match("*")){lex();generator=true}token=lookahead;id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(strict){if(isRestrictedWord(token.value)){throwErrorTolerant(token,Messages.StrictFunctionName)}}else{if(isRestrictedWord(token.value)){firstRestricted=token;message=Messages.StrictFunctionName}else if(isStrictModeReservedWord(token.value)){firstRestricted=token;message=Messages.StrictReservedWord}}tmp=parseParams(firstRestricted);firstRestricted=tmp.firstRestricted;if(tmp.message){message=tmp.message}previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=generator;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=isAsync;body=parseFunctionSourceElements();if(strict&&firstRestricted){throwError(firstRestricted,message)}if(strict&&tmp.stricted){throwErrorTolerant(tmp.stricted,message)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createFunctionDeclaration(id,tmp.params,tmp.defaults,body,tmp.rest,generator,false,isAsync,tmp.returnType,typeParameters))}function parseFunctionExpression(){var token,id=null,firstRestricted,message,tmp,body,generator,isAsync,previousStrict,previousYieldAllowed,previousAwaitAllowed,marker=markerCreate(),typeParameters;isAsync=false;if(matchAsync()){lex();isAsync=true}expectKeyword("function");generator=false;if(match("*")){lex();generator=true}if(!match("(")){if(!match("<")){token=lookahead;id=parseVariableIdentifier();if(strict){if(isRestrictedWord(token.value)){throwErrorTolerant(token,Messages.StrictFunctionName)}}else{if(isRestrictedWord(token.value)){firstRestricted=token;message=Messages.StrictFunctionName}else if(isStrictModeReservedWord(token.value)){firstRestricted=token;message=Messages.StrictReservedWord}}}if(match("<")){typeParameters=parseTypeParameterDeclaration()}}tmp=parseParams(firstRestricted);firstRestricted=tmp.firstRestricted;if(tmp.message){message=tmp.message}previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=generator;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=isAsync;body=parseFunctionSourceElements();if(strict&&firstRestricted){throwError(firstRestricted,message)}if(strict&&tmp.stricted){throwErrorTolerant(tmp.stricted,message)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createFunctionExpression(id,tmp.params,tmp.defaults,body,tmp.rest,generator,false,isAsync,tmp.returnType,typeParameters))}function parseYieldExpression(){var delegateFlag,expr,marker=markerCreate();expectKeyword("yield",!strict);delegateFlag=false;if(match("*")){lex();delegateFlag=true}expr=parseAssignmentExpression();return markerApply(marker,delegate.createYieldExpression(expr,delegateFlag))}function parseAwaitExpression(){var expr,marker=markerCreate();expectContextualKeyword("await");expr=parseAssignmentExpression();return markerApply(marker,delegate.createAwaitExpression(expr))}function parseMethodDefinition(existingPropNames,key,isStatic,generator,computed){var token,param,propType,isValidDuplicateProp=false,isAsync,typeParameters,tokenValue,returnType,annotationMarker;propType=isStatic?ClassPropertyType.static:ClassPropertyType.prototype;if(generator){return delegate.createMethodDefinition(propType,"",key,parsePropertyMethodFunction({generator:true}))}tokenValue=key.type==="Identifier"&&key.name;if(tokenValue==="get"&&!match("(")){key=parseObjectPropertyKey();if(existingPropNames[propType].hasOwnProperty(key.name)){isValidDuplicateProp=existingPropNames[propType][key.name].get===undefined&&existingPropNames[propType][key.name].data===undefined&&existingPropNames[propType][key.name].set!==undefined;if(!isValidDuplicateProp){throwError(key,Messages.IllegalDuplicateClassProperty)}}else{existingPropNames[propType][key.name]={}}existingPropNames[propType][key.name].get=true;expect("(");expect(")");if(match(":")){returnType=parseTypeAnnotation()}return delegate.createMethodDefinition(propType,"get",key,parsePropertyFunction({generator:false,returnType:returnType}))}if(tokenValue==="set"&&!match("(")){key=parseObjectPropertyKey();if(existingPropNames[propType].hasOwnProperty(key.name)){isValidDuplicateProp=existingPropNames[propType][key.name].set===undefined&&existingPropNames[propType][key.name].data===undefined&&existingPropNames[propType][key.name].get!==undefined;if(!isValidDuplicateProp){throwError(key,Messages.IllegalDuplicateClassProperty)}}else{existingPropNames[propType][key.name]={}}existingPropNames[propType][key.name].set=true;expect("(");token=lookahead;param=[parseTypeAnnotatableIdentifier()];expect(")");if(match(":")){returnType=parseTypeAnnotation()}return delegate.createMethodDefinition(propType,"set",key,parsePropertyFunction({params:param,generator:false,name:token,returnType:returnType}))}if(match("<")){typeParameters=parseTypeParameterDeclaration()}isAsync=tokenValue==="async"&&!match("(");if(isAsync){key=parseObjectPropertyKey()}if(existingPropNames[propType].hasOwnProperty(key.name)){throwError(key,Messages.IllegalDuplicateClassProperty)}else{existingPropNames[propType][key.name]={}}existingPropNames[propType][key.name].data=true;return delegate.createMethodDefinition(propType,"",key,parsePropertyMethodFunction({generator:false,async:isAsync,typeParameters:typeParameters}))}function parseClassProperty(existingPropNames,key,computed,isStatic){var typeAnnotation;typeAnnotation=parseTypeAnnotation();expect(";");return delegate.createClassProperty(key,typeAnnotation,computed,isStatic)}function parseClassElement(existingProps){var computed,generator=false,key,marker=markerCreate(),isStatic=false;if(match(";")){lex();return}if(lookahead.value==="static"){lex();isStatic=true}if(match("*")){lex();generator=true}computed=lookahead.value==="[";key=parseObjectPropertyKey();if(!generator&&lookahead.value===":"){return markerApply(marker,parseClassProperty(existingProps,key,computed,isStatic))}return markerApply(marker,parseMethodDefinition(existingProps,key,isStatic,generator,computed))}function parseClassBody(){var classElement,classElements=[],existingProps={},marker=markerCreate();existingProps[ClassPropertyType.static]={};existingProps[ClassPropertyType.prototype]={};expect("{");while(index<length){if(match("}")){break}classElement=parseClassElement(existingProps);if(typeof classElement!=="undefined"){classElements.push(classElement)}}expect("}");return markerApply(marker,delegate.createClassBody(classElements))}function parseClassImplements(){var id,implemented=[],marker,typeParameters;expectContextualKeyword("implements");while(index<length){marker=markerCreate();id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterInstantiation()}else{typeParameters=null}implemented.push(markerApply(marker,delegate.createClassImplements(id,typeParameters)));if(!match(",")){break}expect(",")}return implemented}function parseClassExpression(){var id,implemented,previousYieldAllowed,superClass=null,superTypeParameters,marker=markerCreate(),typeParameters;expectKeyword("class");if(!matchKeyword("extends")&&!matchContextualKeyword("implements")&&!match("{")){id=parseVariableIdentifier()}if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(matchKeyword("extends")){expectKeyword("extends");previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=false;superClass=parseLeftHandSideExpressionAllowCall();if(match("<")){superTypeParameters=parseTypeParameterInstantiation()}state.yieldAllowed=previousYieldAllowed}if(matchContextualKeyword("implements")){implemented=parseClassImplements()}return markerApply(marker,delegate.createClassExpression(id,superClass,parseClassBody(),typeParameters,superTypeParameters,implemented))}function parseClassDeclaration(){var id,implemented,previousYieldAllowed,superClass=null,superTypeParameters,marker=markerCreate(),typeParameters;expectKeyword("class");id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(matchKeyword("extends")){expectKeyword("extends");previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=false;superClass=parseLeftHandSideExpressionAllowCall();if(match("<")){superTypeParameters=parseTypeParameterInstantiation()}state.yieldAllowed=previousYieldAllowed}if(matchContextualKeyword("implements")){implemented=parseClassImplements()}return markerApply(marker,delegate.createClassDeclaration(id,superClass,parseClassBody(),typeParameters,superTypeParameters,implemented))}function parseSourceElement(){var token;if(lookahead.type===Token.Keyword){switch(lookahead.value){case"const":case"let":return parseConstLetDeclaration(lookahead.value);case"function":return parseFunctionDeclaration();default:return parseStatement()}}if(matchContextualKeyword("type")&&lookahead2().type===Token.Identifier){return parseTypeAlias()}if(matchContextualKeyword("interface")&&lookahead2().type===Token.Identifier){return parseInterface()}if(matchContextualKeyword("declare")){token=lookahead2();if(token.type===Token.Keyword){switch(token.value){case"class":return parseDeclareClass();case"function":return parseDeclareFunction();case"var":return parseDeclareVariable()}}else if(token.type===Token.Identifier&&token.value==="module"){return parseDeclareModule()}}if(lookahead.type!==Token.EOF){return parseStatement()}}function parseProgramElement(){if(lookahead.type===Token.Keyword){switch(lookahead.value){case"export":return parseExportDeclaration();case"import":return parseImportDeclaration()}}return parseSourceElement()}function parseProgramElements(){var sourceElement,sourceElements=[],token,directive,firstRestricted;while(index<length){token=lookahead;if(token.type!==Token.StringLiteral){break}sourceElement=parseProgramElement();sourceElements.push(sourceElement);if(sourceElement.expression.type!==Syntax.Literal){break}directive=source.slice(token.range[0]+1,token.range[1]-1);if(directive==="use strict"){strict=true;if(firstRestricted){throwErrorTolerant(firstRestricted,Messages.StrictOctalLiteral)}}else{if(!firstRestricted&&token.octal){firstRestricted=token}}}while(index<length){sourceElement=parseProgramElement();if(typeof sourceElement==="undefined"){break}sourceElements.push(sourceElement)}return sourceElements}function parseProgram(){var body,marker=markerCreate();strict=false;peek();body=parseProgramElements();return markerApply(marker,delegate.createProgram(body))}function addComment(type,value,start,end,loc){var comment;assert(typeof start==="number","Comment must have valid position");if(state.lastCommentStart>=start){return}state.lastCommentStart=start;comment={type:type,value:value};if(extra.range){comment.range=[start,end]}if(extra.loc){comment.loc=loc}extra.comments.push(comment);if(extra.attachComment){extra.leadingComments.push(comment);extra.trailingComments.push(comment)}}function scanComment(){var comment,ch,loc,start,blockComment,lineComment;comment="";blockComment=false;lineComment=false;while(index<length){ch=source[index];if(lineComment){ch=source[index++];if(isLineTerminator(ch.charCodeAt(0))){loc.end={line:lineNumber,column:index-lineStart-1};lineComment=false;addComment("Line",comment,start,index-1,loc);if(ch==="\r"&&source[index]==="\n"){++index}++lineNumber;lineStart=index;comment=""}else if(index>=length){lineComment=false;comment+=ch;loc.end={line:lineNumber,column:length-lineStart};addComment("Line",comment,start,length,loc)}else{comment+=ch}}else if(blockComment){if(isLineTerminator(ch.charCodeAt(0))){if(ch==="\r"){++index;comment+="\r"}if(ch!=="\r"||source[index]==="\n"){comment+=source[index];++lineNumber;++index;lineStart=index;if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}}else{ch=source[index++];if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}comment+=ch;if(ch==="*"){ch=source[index];if(ch==="/"){comment=comment.substr(0,comment.length-1);blockComment=false;++index;loc.end={line:lineNumber,column:index-lineStart};addComment("Block",comment,start,index,loc);comment=""}}}}else if(ch==="/"){ch=source[index+1];if(ch==="/"){loc={start:{line:lineNumber,column:index-lineStart}};
start=index;index+=2;lineComment=true;if(index>=length){loc.end={line:lineNumber,column:index-lineStart};lineComment=false;addComment("Line",comment,start,index,loc)}}else if(ch==="*"){start=index;index+=2;blockComment=true;loc={start:{line:lineNumber,column:index-lineStart-2}};if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}else{break}}else if(isWhiteSpace(ch.charCodeAt(0))){++index}else if(isLineTerminator(ch.charCodeAt(0))){++index;if(ch==="\r"&&source[index]==="\n"){++index}++lineNumber;lineStart=index}else{break}}}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 getQualifiedXJSName(object){if(object.type===Syntax.XJSIdentifier){return object.name}if(object.type===Syntax.XJSNamespacedName){return object.namespace.name+":"+object.name.name}if(object.type===Syntax.XJSMemberExpression){return getQualifiedXJSName(object.object)+"."+getQualifiedXJSName(object.property)}}function isXJSIdentifierStart(ch){return ch!==92&&isIdentifierStart(ch)}function isXJSIdentifierPart(ch){return ch!==92&&(ch===45||isIdentifierPart(ch))}function scanXJSIdentifier(){var ch,start,value="";start=index;while(index<length){ch=source.charCodeAt(index);if(!isXJSIdentifierPart(ch)){break}value+=source[index++]}return{type:Token.XJSIdentifier,value:value,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanXJSEntity(){var ch,str="",start=index,count=0,code;ch=source[index];assert(ch==="&","Entity must start with an ampersand");index++;while(index<length&&count++<10){ch=source[index++];if(ch===";"){break}str+=ch}if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){code=+("0"+str.substr(1))}else{code=+str.substr(1).replace(Regex.LeadingZeros,"")}if(!isNaN(code)){return String.fromCharCode(code)}}else if(XHTMLEntities[str]){return XHTMLEntities[str]}}index=start+1;return"&"}function scanXJSText(stopChars){var ch,str="",start;start=index;while(index<length){ch=source[index];if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=scanXJSEntity()}else{index++;if(ch==="\r"&&source[index]==="\n"){str+=ch;ch=source[index];index++}if(isLineTerminator(ch.charCodeAt(0))){++lineNumber;lineStart=index}str+=ch}}return{type:Token.XJSText,value:str,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanXJSStringLiteral(){var innerToken,quote,start;quote=source[index];assert(quote==="'"||quote==='"',"String literal must starts with a quote");start=index;++index;innerToken=scanXJSText([quote]);if(quote!==source[index]){throwError({},Messages.UnexpectedToken,"ILLEGAL")}++index;innerToken.range=[start,index];return innerToken}function advanceXJSChild(){var ch=source.charCodeAt(index);if(ch!==123&&ch!==60){return scanXJSText(["<","{"])}return scanPunctuator()}function parseXJSIdentifier(){var token,marker=markerCreate();if(lookahead.type!==Token.XJSIdentifier){throwUnexpected(lookahead)}token=lex();return markerApply(marker,delegate.createXJSIdentifier(token.value))}function parseXJSNamespacedName(){var namespace,name,marker=markerCreate();namespace=parseXJSIdentifier();expect(":");name=parseXJSIdentifier();return markerApply(marker,delegate.createXJSNamespacedName(namespace,name))}function parseXJSMemberExpression(){var marker=markerCreate(),expr=parseXJSIdentifier();while(match(".")){lex();expr=markerApply(marker,delegate.createXJSMemberExpression(expr,parseXJSIdentifier()))}return expr}function parseXJSElementName(){if(lookahead2().value===":"){return parseXJSNamespacedName()}if(lookahead2().value==="."){return parseXJSMemberExpression()}return parseXJSIdentifier()}function parseXJSAttributeName(){if(lookahead2().value===":"){return parseXJSNamespacedName()}return parseXJSIdentifier()}function parseXJSAttributeValue(){var value,marker;if(match("{")){value=parseXJSExpressionContainer();if(value.expression.type===Syntax.XJSEmptyExpression){throwError(value,"XJS attributes must only be assigned a non-empty "+"expression")}}else if(match("<")){value=parseXJSElement()}else if(lookahead.type===Token.XJSText){marker=markerCreate();value=markerApply(marker,delegate.createLiteral(lex()))}else{throwError({},Messages.InvalidXJSAttributeValue)}return value}function parseXJSEmptyExpression(){var marker=markerCreatePreserveWhitespace();while(source.charAt(index)!=="}"){index++}return markerApply(marker,delegate.createXJSEmptyExpression())}function parseXJSExpressionContainer(){var expression,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=false;expect("{");if(match("}")){expression=parseXJSEmptyExpression()}else{expression=parseExpression()}state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;expect("}");return markerApply(marker,delegate.createXJSExpressionContainer(expression))}function parseXJSSpreadAttribute(){var expression,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=false;expect("{");expect("...");expression=parseAssignmentExpression();state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;expect("}");return markerApply(marker,delegate.createXJSSpreadAttribute(expression))}function parseXJSAttribute(){var name,marker;if(match("{")){return parseXJSSpreadAttribute()}marker=markerCreate();name=parseXJSAttributeName();if(match("=")){lex();return markerApply(marker,delegate.createXJSAttribute(name,parseXJSAttributeValue()))}return markerApply(marker,delegate.createXJSAttribute(name))}function parseXJSChild(){var token,marker;if(match("{")){token=parseXJSExpressionContainer()}else if(lookahead.type===Token.XJSText){marker=markerCreatePreserveWhitespace();token=markerApply(marker,delegate.createLiteral(lex()))}else{token=parseXJSElement()}return token}function parseXJSClosingElement(){var name,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=true;expect("<");expect("/");name=parseXJSElementName();state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;expect(">");return markerApply(marker,delegate.createXJSClosingElement(name))}function parseXJSOpeningElement(){var name,attribute,attributes=[],selfClosing=false,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=true;expect("<");name=parseXJSElementName();while(index<length&&lookahead.value!=="/"&&lookahead.value!==">"){attributes.push(parseXJSAttribute())}state.inXJSTag=origInXJSTag;if(lookahead.value==="/"){expect("/");state.inXJSChild=origInXJSChild;expect(">");selfClosing=true}else{state.inXJSChild=true;expect(">")}return markerApply(marker,delegate.createXJSOpeningElement(name,attributes,selfClosing))}function parseXJSElement(){var openingElement,closingElement=null,children=[],origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;openingElement=parseXJSOpeningElement();if(!openingElement.selfClosing){while(index<length){state.inXJSChild=false;if(lookahead.value==="<"&&lookahead2().value==="/"){break}state.inXJSChild=true;children.push(parseXJSChild())}state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;closingElement=parseXJSClosingElement();if(getQualifiedXJSName(closingElement.name)!==getQualifiedXJSName(openingElement.name)){throwError({},Messages.ExpectedXJSClosingTag,getQualifiedXJSName(openingElement.name))}}if(!origInXJSChild&&match("<")){throwError(lookahead,Messages.AdjacentXJSElements)}return markerApply(marker,delegate.createXJSElement(openingElement,closingElement,children))}function parseTypeAlias(){var id,marker=markerCreate(),typeParameters=null,right;expectContextualKeyword("type");id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}expect("=");right=parseType();consumeSemicolon();return markerApply(marker,delegate.createTypeAlias(id,typeParameters,right))}function parseInterfaceExtends(){var marker=markerCreate(),id,typeParameters=null;id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterInstantiation()}return markerApply(marker,delegate.createInterfaceExtends(id,typeParameters))}function parseInterfaceish(marker,allowStatic){var body,bodyMarker,extended=[],id,typeParameters=null;id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(matchKeyword("extends")){expectKeyword("extends");while(index<length){extended.push(parseInterfaceExtends());if(!match(",")){break}expect(",")}}bodyMarker=markerCreate();body=markerApply(bodyMarker,parseObjectType(allowStatic));return markerApply(marker,delegate.createInterface(id,typeParameters,body,extended))}function parseInterface(){var body,bodyMarker,extended=[],id,marker=markerCreate(),typeParameters=null;expectContextualKeyword("interface");return parseInterfaceish(marker,false)}function parseDeclareClass(){var marker=markerCreate(),ret;expectContextualKeyword("declare");expectKeyword("class");ret=parseInterfaceish(marker,true);ret.type=Syntax.DeclareClass;return ret}function parseDeclareFunction(){var id,idMarker,marker=markerCreate(),params,returnType,rest,tmp,typeParameters=null,value,valueMarker;expectContextualKeyword("declare");expectKeyword("function");idMarker=markerCreate();id=parseVariableIdentifier();valueMarker=markerCreate();if(match("<")){typeParameters=parseTypeParameterDeclaration()}expect("(");tmp=parseFunctionTypeParams();params=tmp.params;rest=tmp.rest;expect(")");expect(":");returnType=parseType();value=markerApply(valueMarker,delegate.createFunctionTypeAnnotation(params,returnType,rest,typeParameters));id.typeAnnotation=markerApply(valueMarker,delegate.createTypeAnnotation(value));markerApply(idMarker,id);consumeSemicolon();return markerApply(marker,delegate.createDeclareFunction(id))}function parseDeclareVariable(){var id,marker=markerCreate();expectContextualKeyword("declare");expectKeyword("var");id=parseTypeAnnotatableIdentifier();consumeSemicolon();return markerApply(marker,delegate.createDeclareVariable(id))}function parseDeclareModule(){var body=[],bodyMarker,id,idMarker,marker=markerCreate(),token;expectContextualKeyword("declare");expectContextualKeyword("module");if(lookahead.type===Token.StringLiteral){if(strict&&lookahead.octal){throwErrorTolerant(lookahead,Messages.StrictOctalLiteral)}idMarker=markerCreate();id=markerApply(idMarker,delegate.createLiteral(lex()))}else{id=parseVariableIdentifier()}bodyMarker=markerCreate();expect("{");while(index<length&&!match("}")){token=lookahead2();switch(token.value){case"class":body.push(parseDeclareClass());break;case"function":body.push(parseDeclareFunction());break;case"var":body.push(parseDeclareVariable());break;default:throwUnexpected(lookahead)}}expect("}");return markerApply(marker,delegate.createDeclareModule(id,markerApply(bodyMarker,delegate.createBlockStatement(body))))}function collectToken(){var start,loc,token,range,value,entry;if(!state.inXJSChild){skipComment()}start=index;loc={start:{line:lineNumber,column:index-lineStart}};token=extra.advance();loc.end={line:lineNumber,column:index-lineStart};if(token.type!==Token.EOF){range=[token.range[0],token.range[1]];value=source.slice(token.range[0],token.range[1]);entry={type:TokenName[token.type],value:value,range:range,loc:loc};if(token.regex){entry.regex={pattern:token.regex.pattern,flags:token.regex.flags}}extra.tokens.push(entry)}return token}function collectRegex(){var pos,loc,regex,token;skipComment();pos=index;loc={start:{line:lineNumber,column:index-lineStart}};regex=extra.scanRegExp();loc.end={line:lineNumber,column:index-lineStart};if(!extra.tokenize){if(extra.tokens.length>0){token=extra.tokens[extra.tokens.length-1];if(token.range[0]===pos&&token.type==="Punctuator"){if(token.value==="/"||token.value==="/="){extra.tokens.pop()}}}extra.tokens.push({type:"RegularExpression",value:regex.literal,regex:regex.regex,range:[pos,index],loc:loc})}return regex}function filterTokenLocation(){var i,entry,token,tokens=[];for(i=0;i<extra.tokens.length;++i){entry=extra.tokens[i];token={type:entry.type,value:entry.value};if(entry.regex){token.regex={pattern:entry.regex.pattern,flags:entry.regex.flags}}if(extra.range){token.range=entry.range}if(extra.loc){token.loc=entry.loc}tokens.push(token)}extra.tokens=tokens}function patch(){if(extra.comments){extra.skipComment=skipComment;skipComment=scanComment}if(typeof extra.tokens!=="undefined"){extra.advance=advance;extra.scanRegExp=scanRegExp;advance=collectToken;scanRegExp=collectRegex}}function unpatch(){if(typeof extra.skipComment==="function"){skipComment=extra.skipComment}if(typeof extra.scanRegExp==="function"){advance=extra.advance;scanRegExp=extra.scanRegExp}}function extend(object,properties){var entry,result={};for(entry in object){if(object.hasOwnProperty(entry)){result[entry]=object[entry]}}for(entry in properties){if(properties.hasOwnProperty(entry)){result[entry]=properties[entry]}}return result}function tokenize(code,options){var toString,token,tokens;toString=String;if(typeof code!=="string"&&!(code instanceof String)){code=toString(code)}delegate=SyntaxTreeDelegate;source=code;index=0;lineNumber=source.length>0?1:0;lineStart=0;length=source.length;lookahead=null;state={allowKeyword:true,allowIn:true,labelSet:{},inFunctionBody:false,inIteration:false,inSwitch:false,lastCommentStart:-1};extra={};options=options||{};options.tokens=true;extra.tokens=[];extra.tokenize=true;extra.openParenToken=-1;extra.openCurlyToken=-1;extra.range=typeof options.range==="boolean"&&options.range;extra.loc=typeof options.loc==="boolean"&&options.loc;if(typeof options.comment==="boolean"&&options.comment){extra.comments=[]}if(typeof options.tolerant==="boolean"&&options.tolerant){extra.errors=[]}if(length>0){if(typeof source[0]==="undefined"){if(code instanceof String){source=code.valueOf()}}}patch();try{peek();if(lookahead.type===Token.EOF){return extra.tokens}token=lex();while(lookahead.type!==Token.EOF){try{token=lex()}catch(lexError){token=lookahead;if(extra.errors){extra.errors.push(lexError);break}else{throw lexError}}}filterTokenLocation();tokens=extra.tokens;if(typeof extra.comments!=="undefined"){tokens.comments=extra.comments}if(typeof extra.errors!=="undefined"){tokens.errors=extra.errors}}catch(e){throw e}finally{unpatch();extra={}}return tokens}function parse(code,options){var program,toString;toString=String;if(typeof code!=="string"&&!(code instanceof String)){code=toString(code)}delegate=SyntaxTreeDelegate;source=code;index=0;lineNumber=source.length>0?1:0;lineStart=0;length=source.length;lookahead=null;state={allowKeyword:false,allowIn:true,labelSet:{},parenthesizedCount:0,inFunctionBody:false,inIteration:false,inSwitch:false,inXJSChild:false,inXJSTag:false,inType:false,lastCommentStart:-1,yieldAllowed:false,awaitAllowed:false};extra={};if(typeof options!=="undefined"){extra.range=typeof options.range==="boolean"&&options.range;extra.loc=typeof options.loc==="boolean"&&options.loc;extra.attachComment=typeof options.attachComment==="boolean"&&options.attachComment;if(extra.loc&&options.source!==null&&options.source!==undefined){delegate=extend(delegate,{postProcess:function(node){node.loc.source=toString(options.source);return node}})}if(typeof options.tokens==="boolean"&&options.tokens){extra.tokens=[]}if(typeof options.comment==="boolean"&&options.comment){extra.comments=[]}if(typeof options.tolerant==="boolean"&&options.tolerant){extra.errors=[]}if(extra.attachComment){extra.range=true;extra.comments=[];extra.bottomRightStack=[];extra.trailingComments=[];extra.leadingComments=[]}}if(length>0){if(typeof source[0]==="undefined"){if(code instanceof String){source=code.valueOf()}}}patch();try{program=parseProgram();if(typeof extra.comments!=="undefined"){program.comments=extra.comments}if(typeof extra.tokens!=="undefined"){filterTokenLocation();program.tokens=extra.tokens}if(typeof extra.errors!=="undefined"){program.errors=extra.errors}}catch(e){throw e}finally{unpatch();extra={}}return program}exports.version="8001.1001.0-dev-harmony-fb";exports.tokenize=tokenize;exports.parse=parse;exports.Syntax=function(){var name,types={};if(typeof Object.create==="function"){types=Object.create(null)}for(name in Syntax){if(Syntax.hasOwnProperty(name)){types[name]=Syntax[name]}}if(typeof Object.freeze==="function"){Object.freeze(types)}return types}()})},{}],145:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var linesModule=require("./lines");var fromString=linesModule.fromString;var Lines=linesModule.Lines;var concat=linesModule.concat;var comparePos=require("./util").comparePos;var childNodesCacheKey=require("private").makeUniqueKey();function getSortedChildNodes(node,resultArray){if(!node){return}if(resultArray){if(n.Node.check(node)&&n.SourceLocation.check(node.loc)){for(var i=resultArray.length-1;i>=0;--i){if(comparePos(resultArray[i].loc.end,node.loc.start)<=0){break}}resultArray.splice(i+1,0,node);return}}else if(node[childNodesCacheKey]){return node[childNodesCacheKey]}var names;if(isArray.check(node)){names=Object.keys(node)}else if(isObject.check(node)){names=types.getFieldNames(node)}else{return}if(!resultArray){Object.defineProperty(node,childNodesCacheKey,{value:resultArray=[],enumerable:false})}for(var i=0,nameCount=names.length;i<nameCount;++i){getSortedChildNodes(node[names[i]],resultArray)}return resultArray}function decorateComment(node,comment){var childNodes=getSortedChildNodes(node);var left=0,right=childNodes.length;while(left<right){var middle=left+right>>1;var child=childNodes[middle];if(comparePos(child.loc.start,comment.loc.start)<=0&&comparePos(comment.loc.end,child.loc.end)<=0){decorateComment(comment.enclosingNode=child,comment);return}if(comparePos(child.loc.end,comment.loc.start)<=0){var precedingNode=child;left=middle+1;continue}if(comparePos(comment.loc.end,child.loc.start)<=0){var followingNode=child;right=middle;continue}throw new Error("Comment location overlaps with node location")}if(precedingNode){comment.precedingNode=precedingNode}if(followingNode){comment.followingNode=followingNode}}exports.attach=function(comments,ast,lines){if(!isArray.check(comments)){return}var tiesToBreak=[];comments.forEach(function(comment){comment.loc.lines=lines;decorateComment(ast,comment);var pn=comment.precedingNode;var en=comment.enclosingNode;var fn=comment.followingNode;if(pn&&fn){var tieCount=tiesToBreak.length;if(tieCount>0){var lastTie=tiesToBreak[tieCount-1];assert.strictEqual(lastTie.precedingNode===comment.precedingNode,lastTie.followingNode===comment.followingNode);if(lastTie.followingNode!==comment.followingNode){breakTies(tiesToBreak,lines)}}tiesToBreak.push(comment)}else if(pn){breakTies(tiesToBreak,lines);Comments.forNode(pn).addTrailing(comment)}else if(fn){breakTies(tiesToBreak,lines);Comments.forNode(fn).addLeading(comment)}else if(en){breakTies(tiesToBreak,lines);Comments.forNode(en).addDangling(comment)}else{throw new Error("AST contains no nodes at all?")}});breakTies(tiesToBreak,lines)};function breakTies(tiesToBreak,lines){var tieCount=tiesToBreak.length;if(tieCount===0){return}var pn=tiesToBreak[0].precedingNode;var fn=tiesToBreak[0].followingNode;var gapEndPos=fn.loc.start;for(var indexOfFirstLeadingComment=tieCount;indexOfFirstLeadingComment>0;--indexOfFirstLeadingComment){var comment=tiesToBreak[indexOfFirstLeadingComment-1];assert.strictEqual(comment.precedingNode,pn);assert.strictEqual(comment.followingNode,fn);var gap=lines.sliceString(comment.loc.end,gapEndPos);if(/\S/.test(gap)){break}gapEndPos=comment.loc.start}while(indexOfFirstLeadingComment<=tieCount&&(comment=tiesToBreak[indexOfFirstLeadingComment])&&comment.type==="Line"&&comment.loc.start.column>fn.loc.start.column){++indexOfFirstLeadingComment}tiesToBreak.forEach(function(comment,i){if(i<indexOfFirstLeadingComment){Comments.forNode(pn).addTrailing(comment)}else{Comments.forNode(fn).addLeading(comment)}});tiesToBreak.length=0}function Comments(){assert.ok(this instanceof Comments);this.leading=[];this.dangling=[];this.trailing=[]}var Cp=Comments.prototype;Comments.forNode=function forNode(node){var comments=node.comments;if(!comments){Object.defineProperty(node,"comments",{value:comments=new Comments,enumerable:false})}return comments};Cp.forEach=function forEach(callback,context){this.leading.forEach(callback,context);this.trailing.forEach(callback,context)};Cp.addLeading=function addLeading(comment){this.leading.push(comment)};Cp.addDangling=function addDangling(comment){this.dangling.push(comment)};Cp.addTrailing=function addTrailing(comment){comment.trailing=true;if(comment.type==="Block"){this.trailing.push(comment)}else{this.leading.push(comment)}};function printLeadingComment(comment,options){var loc=comment.loc;var lines=loc&&loc.lines;var parts=[];if(comment.type==="Block"){parts.push("/*",fromString(comment.value,options),"*/")}else if(comment.type==="Line"){parts.push("//",fromString(comment.value,options))}else assert.fail(comment.type);if(comment.trailing){parts.push("\n")}else if(lines instanceof Lines){var trailingSpace=lines.slice(loc.end,lines.skipSpaces(loc.end));if(trailingSpace.length===1){parts.push(trailingSpace)}else{parts.push(new Array(trailingSpace.length).join("\n"))}}else{parts.push("\n")}return concat(parts).stripMargin(loc?loc.start.column:0)}function printTrailingComment(comment,options){var loc=comment.loc;var lines=loc&&loc.lines;var parts=[];if(lines instanceof Lines){var fromPos=lines.skipSpaces(loc.start,true)||lines.firstPos();var leadingSpace=lines.slice(fromPos,loc.start);if(leadingSpace.length===1){parts.push(leadingSpace)}else{parts.push(new Array(leadingSpace.length).join("\n"))}}if(comment.type==="Block"){parts.push("/*",fromString(comment.value,options),"*/")}else if(comment.type==="Line"){parts.push("//",fromString(comment.value,options),"\n")}else assert.fail(comment.type);return concat(parts).stripMargin(loc?loc.start.column:0,true)}exports.printComments=function(comments,innerLines,options){if(innerLines){assert.ok(innerLines instanceof Lines)}else{innerLines=fromString("")}if(!comments||!(comments.leading.length+comments.trailing.length)){return innerLines}var parts=[];comments.leading.forEach(function(comment){parts.push(printLeadingComment(comment,options))});parts.push(innerLines);comments.trailing.forEach(function(comment){assert.strictEqual(comment.type,"Block");parts.push(printTrailingComment(comment,options))});return concat(parts)}},{"./lines":146,"./types":152,"./util":153,assert:90,"private":122}],146:[function(require,module,exports){var assert=require("assert");var sourceMap=require("source-map");var normalizeOptions=require("./options").normalize;var secretKey=require("private").makeUniqueKey();var types=require("./types");var isString=types.builtInTypes.string;var comparePos=require("./util").comparePos;var Mapping=require("./mapping");function getSecret(lines){return lines[secretKey]}function Lines(infos,sourceFileName){assert.ok(this instanceof Lines);assert.ok(infos.length>0);if(sourceFileName){isString.assert(sourceFileName)}else{sourceFileName=null}Object.defineProperty(this,secretKey,{value:{infos:infos,mappings:[],name:sourceFileName,cachedSourceMap:null}});if(sourceFileName){getSecret(this).mappings.push(new Mapping(this,{start:this.firstPos(),end:this.lastPos()}))}}exports.Lines=Lines;var Lp=Lines.prototype;Object.defineProperties(Lp,{length:{get:function(){return getSecret(this).infos.length}},name:{get:function(){return getSecret(this).name}}});function copyLineInfo(info){return{line:info.line,indent:info.indent,sliceStart:info.sliceStart,sliceEnd:info.sliceEnd}}var fromStringCache={};var hasOwn=fromStringCache.hasOwnProperty;var maxCacheKeyLen=10;function countSpaces(spaces,tabWidth){var count=0;var len=spaces.length;for(var i=0;i<len;++i){var ch=spaces.charAt(i);if(ch===" "){count+=1}else if(ch===" "){assert.strictEqual(typeof tabWidth,"number");assert.ok(tabWidth>0);var next=Math.ceil(count/tabWidth)*tabWidth;if(next===count){count+=tabWidth}else{count=next}}else if(ch==="\r"){}else{assert.fail("unexpected whitespace character",ch)}}return count}exports.countSpaces=countSpaces;var leadingSpaceExp=/^\s*/;function fromString(string,options){if(string instanceof Lines)return string;string+="";var tabWidth=options&&options.tabWidth;var tabless=string.indexOf(" ")<0;var cacheable=!options&&tabless&&string.length<=maxCacheKeyLen;assert.ok(tabWidth||tabless,"No tab width specified but encountered tabs in string\n"+string);if(cacheable&&hasOwn.call(fromStringCache,string))return fromStringCache[string];var lines=new Lines(string.split("\n").map(function(line){var spaces=leadingSpaceExp.exec(line)[0];return{line:line,indent:countSpaces(spaces,tabWidth),sliceStart:spaces.length,sliceEnd:line.length}}),normalizeOptions(options).sourceFileName);if(cacheable)fromStringCache[string]=lines;return lines}exports.fromString=fromString;function isOnlyWhitespace(string){return!/\S/.test(string)}Lp.toString=function(options){return this.sliceString(this.firstPos(),this.lastPos(),options)};Lp.getSourceMap=function(sourceMapName,sourceRoot){if(!sourceMapName){return null}var targetLines=this;function updateJSON(json){json=json||{};isString.assert(sourceMapName);json.file=sourceMapName;if(sourceRoot){isString.assert(sourceRoot);json.sourceRoot=sourceRoot}return json}var secret=getSecret(targetLines);if(secret.cachedSourceMap){return updateJSON(secret.cachedSourceMap.toJSON())}var smg=new sourceMap.SourceMapGenerator(updateJSON());var sourcesToContents={};secret.mappings.forEach(function(mapping){var sourceCursor=mapping.sourceLines.skipSpaces(mapping.sourceLoc.start)||mapping.sourceLines.lastPos();var targetCursor=targetLines.skipSpaces(mapping.targetLoc.start)||targetLines.lastPos();while(comparePos(sourceCursor,mapping.sourceLoc.end)<0&&comparePos(targetCursor,mapping.targetLoc.end)<0){var sourceChar=mapping.sourceLines.charAt(sourceCursor);var targetChar=targetLines.charAt(targetCursor);assert.strictEqual(sourceChar,targetChar);var sourceName=mapping.sourceLines.name;smg.addMapping({source:sourceName,original:{line:sourceCursor.line,column:sourceCursor.column},generated:{line:targetCursor.line,column:targetCursor.column}});if(!hasOwn.call(sourcesToContents,sourceName)){var sourceContent=mapping.sourceLines.toString();smg.setSourceContent(sourceName,sourceContent);sourcesToContents[sourceName]=sourceContent}targetLines.nextPos(targetCursor,true);mapping.sourceLines.nextPos(sourceCursor,true)}});secret.cachedSourceMap=smg;return smg.toJSON()};Lp.bootstrapCharAt=function(pos){assert.strictEqual(typeof pos,"object");assert.strictEqual(typeof pos.line,"number");assert.strictEqual(typeof pos.column,"number");var line=pos.line,column=pos.column,strings=this.toString().split("\n"),string=strings[line-1];if(typeof string==="undefined")return"";if(column===string.length&&line<strings.length)return"\n";if(column>=string.length)return"";return string.charAt(column)};Lp.charAt=function(pos){assert.strictEqual(typeof pos,"object");assert.strictEqual(typeof pos.line,"number");assert.strictEqual(typeof pos.column,"number");var line=pos.line,column=pos.column,secret=getSecret(this),infos=secret.infos,info=infos[line-1],c=column;if(typeof info==="undefined"||c<0)return"";var indent=this.getIndentAt(line);if(c<indent)return" ";c+=info.sliceStart-indent;if(c===info.sliceEnd&&line<this.length)return"\n";if(c>=info.sliceEnd)return"";return info.line.charAt(c)};Lp.stripMargin=function(width,skipFirstLine){if(width===0)return this;assert.ok(width>0,"negative margin: "+width);if(skipFirstLine&&this.length===1)return this;var secret=getSecret(this);var lines=new Lines(secret.infos.map(function(info,i){if(info.line&&(i>0||!skipFirstLine)){info=copyLineInfo(info);info.indent=Math.max(0,info.indent-width)}return info}));if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){newMappings.push(mapping.indent(width,skipFirstLine,true))})}return lines};Lp.indent=function(by){if(by===0)return this;var secret=getSecret(this);var lines=new Lines(secret.infos.map(function(info){if(info.line){info=copyLineInfo(info);info.indent+=by}return info}));if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){newMappings.push(mapping.indent(by))})}return lines};Lp.indentTail=function(by){if(by===0)return this;if(this.length<2)return this;var secret=getSecret(this);var lines=new Lines(secret.infos.map(function(info,i){if(i>0&&info.line){info=copyLineInfo(info);info.indent+=by}return info}));if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){newMappings.push(mapping.indent(by,true))})}return lines};Lp.getIndentAt=function(line){assert.ok(line>=1,"no line "+line+" (line numbers start from 1)");var secret=getSecret(this),info=secret.infos[line-1];return Math.max(info.indent,0)};Lp.guessTabWidth=function(){var secret=getSecret(this);if(hasOwn.call(secret,"cachedTabWidth")){return secret.cachedTabWidth}var counts=[];var lastIndent=0;for(var line=1,last=this.length;line<=last;++line){var info=secret.infos[line-1];var sliced=info.line.slice(info.sliceStart,info.sliceEnd);if(isOnlyWhitespace(sliced)){continue}var diff=Math.abs(info.indent-lastIndent);
counts[diff]=~~counts[diff]+1;lastIndent=info.indent}var maxCount=-1;var result=2;for(var tabWidth=1;tabWidth<counts.length;tabWidth+=1){if(hasOwn.call(counts,tabWidth)&&counts[tabWidth]>maxCount){maxCount=counts[tabWidth];result=tabWidth}}return secret.cachedTabWidth=result};Lp.isOnlyWhitespace=function(){return isOnlyWhitespace(this.toString())};Lp.isPrecededOnlyByWhitespace=function(pos){var secret=getSecret(this);var info=secret.infos[pos.line-1];var indent=Math.max(info.indent,0);var diff=pos.column-indent;if(diff<=0){return true}var start=info.sliceStart;var end=Math.min(start+diff,info.sliceEnd);var prefix=info.line.slice(start,end);return isOnlyWhitespace(prefix)};Lp.getLineLength=function(line){var secret=getSecret(this),info=secret.infos[line-1];return this.getIndentAt(line)+info.sliceEnd-info.sliceStart};Lp.nextPos=function(pos,skipSpaces){var l=Math.max(pos.line,0),c=Math.max(pos.column,0);if(c<this.getLineLength(l)){pos.column+=1;return skipSpaces?!!this.skipSpaces(pos,false,true):true}if(l<this.length){pos.line+=1;pos.column=0;return skipSpaces?!!this.skipSpaces(pos,false,true):true}return false};Lp.prevPos=function(pos,skipSpaces){var l=pos.line,c=pos.column;if(c<1){l-=1;if(l<1)return false;c=this.getLineLength(l)}else{c=Math.min(c-1,this.getLineLength(l))}pos.line=l;pos.column=c;return skipSpaces?!!this.skipSpaces(pos,true,true):true};Lp.firstPos=function(){return{line:1,column:0}};Lp.lastPos=function(){return{line:this.length,column:this.getLineLength(this.length)}};Lp.skipSpaces=function(pos,backward,modifyInPlace){if(pos){pos=modifyInPlace?pos:{line:pos.line,column:pos.column}}else if(backward){pos=this.lastPos()}else{pos=this.firstPos()}if(backward){while(this.prevPos(pos)){if(!isOnlyWhitespace(this.charAt(pos))&&this.nextPos(pos)){return pos}}return null}else{while(isOnlyWhitespace(this.charAt(pos))){if(!this.nextPos(pos)){return null}}return pos}};Lp.trimLeft=function(){var pos=this.skipSpaces(this.firstPos(),false,true);return pos?this.slice(pos):emptyLines};Lp.trimRight=function(){var pos=this.skipSpaces(this.lastPos(),true,true);return pos?this.slice(this.firstPos(),pos):emptyLines};Lp.trim=function(){var start=this.skipSpaces(this.firstPos(),false,true);if(start===null)return emptyLines;var end=this.skipSpaces(this.lastPos(),true,true);assert.notStrictEqual(end,null);return this.slice(start,end)};Lp.eachPos=function(callback,startPos,skipSpaces){var pos=this.firstPos();if(startPos){pos.line=startPos.line,pos.column=startPos.column}if(skipSpaces&&!this.skipSpaces(pos,false,true)){return}do callback.call(this,pos);while(this.nextPos(pos,skipSpaces))};Lp.bootstrapSlice=function(start,end){var strings=this.toString().split("\n").slice(start.line-1,end.line);strings.push(strings.pop().slice(0,end.column));strings[0]=strings[0].slice(start.column);return fromString(strings.join("\n"))};Lp.slice=function(start,end){if(!end){if(!start){return this}end=this.lastPos()}var secret=getSecret(this);var sliced=secret.infos.slice(start.line-1,end.line);if(start.line===end.line){sliced[0]=sliceInfo(sliced[0],start.column,end.column)}else{assert.ok(start.line<end.line);sliced[0]=sliceInfo(sliced[0],start.column);sliced.push(sliceInfo(sliced.pop(),0,end.column))}var lines=new Lines(sliced);if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){var sliced=mapping.slice(this,start,end);if(sliced){newMappings.push(sliced)}},this)}return lines};function sliceInfo(info,startCol,endCol){var sliceStart=info.sliceStart;var sliceEnd=info.sliceEnd;var indent=Math.max(info.indent,0);var lineLength=indent+sliceEnd-sliceStart;if(typeof endCol==="undefined"){endCol=lineLength}startCol=Math.max(startCol,0);endCol=Math.min(endCol,lineLength);endCol=Math.max(endCol,startCol);if(endCol<indent){indent=endCol;sliceEnd=sliceStart}else{sliceEnd-=lineLength-endCol}lineLength=endCol;lineLength-=startCol;if(startCol<indent){indent-=startCol}else{startCol-=indent;indent=0;sliceStart+=startCol}assert.ok(indent>=0);assert.ok(sliceStart<=sliceEnd);assert.strictEqual(lineLength,indent+sliceEnd-sliceStart);if(info.indent===indent&&info.sliceStart===sliceStart&&info.sliceEnd===sliceEnd){return info}return{line:info.line,indent:indent,sliceStart:sliceStart,sliceEnd:sliceEnd}}Lp.bootstrapSliceString=function(start,end,options){return this.slice(start,end).toString(options)};Lp.sliceString=function(start,end,options){if(!end){if(!start){return this}end=this.lastPos()}options=normalizeOptions(options);var infos=getSecret(this).infos;var parts=[];var tabWidth=options.tabWidth;for(var line=start.line;line<=end.line;++line){var info=infos[line-1];if(line===start.line){if(line===end.line){info=sliceInfo(info,start.column,end.column)}else{info=sliceInfo(info,start.column)}}else if(line===end.line){info=sliceInfo(info,0,end.column)}var indent=Math.max(info.indent,0);var before=info.line.slice(0,info.sliceStart);if(options.reuseWhitespace&&isOnlyWhitespace(before)&&countSpaces(before,options.tabWidth)===indent){parts.push(info.line.slice(0,info.sliceEnd));continue}var tabs=0;var spaces=indent;if(options.useTabs){tabs=Math.floor(indent/tabWidth);spaces-=tabs*tabWidth}var result="";if(tabs>0){result+=new Array(tabs+1).join(" ")}if(spaces>0){result+=new Array(spaces+1).join(" ")}result+=info.line.slice(info.sliceStart,info.sliceEnd);parts.push(result)}return parts.join("\n")};Lp.isEmpty=function(){return this.length<2&&this.getLineLength(1)<1};Lp.join=function(elements){var separator=this;var separatorSecret=getSecret(separator);var infos=[];var mappings=[];var prevInfo;function appendSecret(secret){if(secret===null)return;if(prevInfo){var info=secret.infos[0];var indent=new Array(info.indent+1).join(" ");var prevLine=infos.length;var prevColumn=Math.max(prevInfo.indent,0)+prevInfo.sliceEnd-prevInfo.sliceStart;prevInfo.line=prevInfo.line.slice(0,prevInfo.sliceEnd)+indent+info.line.slice(info.sliceStart,info.sliceEnd);prevInfo.sliceEnd=prevInfo.line.length;if(secret.mappings.length>0){secret.mappings.forEach(function(mapping){mappings.push(mapping.add(prevLine,prevColumn))})}}else if(secret.mappings.length>0){mappings.push.apply(mappings,secret.mappings)}secret.infos.forEach(function(info,i){if(!prevInfo||i>0){prevInfo=copyLineInfo(info);infos.push(prevInfo)}})}function appendWithSeparator(secret,i){if(i>0)appendSecret(separatorSecret);appendSecret(secret)}elements.map(function(elem){var lines=fromString(elem);if(lines.isEmpty())return null;return getSecret(lines)}).forEach(separator.isEmpty()?appendSecret:appendWithSeparator);if(infos.length<1)return emptyLines;var lines=new Lines(infos);getSecret(lines).mappings=mappings;return lines};exports.concat=function(elements){return emptyLines.join(elements)};Lp.concat=function(other){var args=arguments,list=[this];list.push.apply(list,args);assert.strictEqual(list.length,args.length+1);return emptyLines.join(list)};var emptyLines=fromString("")},{"./mapping":147,"./options":148,"./types":152,"./util":153,assert:90,"private":122,"source-map":163}],147:[function(require,module,exports){var assert=require("assert");var types=require("./types");var isString=types.builtInTypes.string;var isNumber=types.builtInTypes.number;var SourceLocation=types.namedTypes.SourceLocation;var Position=types.namedTypes.Position;var linesModule=require("./lines");var comparePos=require("./util").comparePos;function Mapping(sourceLines,sourceLoc,targetLoc){assert.ok(this instanceof Mapping);assert.ok(sourceLines instanceof linesModule.Lines);SourceLocation.assert(sourceLoc);if(targetLoc){assert.ok(isNumber.check(targetLoc.start.line)&&isNumber.check(targetLoc.start.column)&&isNumber.check(targetLoc.end.line)&&isNumber.check(targetLoc.end.column))}else{targetLoc=sourceLoc}Object.defineProperties(this,{sourceLines:{value:sourceLines},sourceLoc:{value:sourceLoc},targetLoc:{value:targetLoc}})}var Mp=Mapping.prototype;module.exports=Mapping;Mp.slice=function(lines,start,end){assert.ok(lines instanceof linesModule.Lines);Position.assert(start);if(end){Position.assert(end)}else{end=lines.lastPos()}var sourceLines=this.sourceLines;var sourceLoc=this.sourceLoc;var targetLoc=this.targetLoc;function skip(name){var sourceFromPos=sourceLoc[name];var targetFromPos=targetLoc[name];var targetToPos=start;if(name==="end"){targetToPos=end}else{assert.strictEqual(name,"start")}return skipChars(sourceLines,sourceFromPos,lines,targetFromPos,targetToPos)}if(comparePos(start,targetLoc.start)<=0){if(comparePos(targetLoc.end,end)<=0){targetLoc={start:subtractPos(targetLoc.start,start.line,start.column),end:subtractPos(targetLoc.end,start.line,start.column)}}else if(comparePos(end,targetLoc.start)<=0){return null}else{sourceLoc={start:sourceLoc.start,end:skip("end")};targetLoc={start:subtractPos(targetLoc.start,start.line,start.column),end:subtractPos(end,start.line,start.column)}}}else{if(comparePos(targetLoc.end,start)<=0){return null}if(comparePos(targetLoc.end,end)<=0){sourceLoc={start:skip("start"),end:sourceLoc.end};targetLoc={start:{line:1,column:0},end:subtractPos(targetLoc.end,start.line,start.column)}}else{sourceLoc={start:skip("start"),end:skip("end")};targetLoc={start:{line:1,column:0},end:subtractPos(end,start.line,start.column)}}}return new Mapping(this.sourceLines,sourceLoc,targetLoc)};Mp.add=function(line,column){return new Mapping(this.sourceLines,this.sourceLoc,{start:addPos(this.targetLoc.start,line,column),end:addPos(this.targetLoc.end,line,column)})};function addPos(toPos,line,column){return{line:toPos.line+line-1,column:toPos.line===1?toPos.column+column:toPos.column}}Mp.subtract=function(line,column){return new Mapping(this.sourceLines,this.sourceLoc,{start:subtractPos(this.targetLoc.start,line,column),end:subtractPos(this.targetLoc.end,line,column)})};function subtractPos(fromPos,line,column){return{line:fromPos.line-line+1,column:fromPos.line===line?fromPos.column-column:fromPos.column}}Mp.indent=function(by,skipFirstLine,noNegativeColumns){if(by===0){return this}var targetLoc=this.targetLoc;var startLine=targetLoc.start.line;var endLine=targetLoc.end.line;if(skipFirstLine&&startLine===1&&endLine===1){return this}targetLoc={start:targetLoc.start,end:targetLoc.end};if(!skipFirstLine||startLine>1){var startColumn=targetLoc.start.column+by;targetLoc.start={line:startLine,column:noNegativeColumns?Math.max(0,startColumn):startColumn}}if(!skipFirstLine||endLine>1){var endColumn=targetLoc.end.column+by;targetLoc.end={line:endLine,column:noNegativeColumns?Math.max(0,endColumn):endColumn}}return new Mapping(this.sourceLines,this.sourceLoc,targetLoc)};function skipChars(sourceLines,sourceFromPos,targetLines,targetFromPos,targetToPos){assert.ok(sourceLines instanceof linesModule.Lines);assert.ok(targetLines instanceof linesModule.Lines);Position.assert(sourceFromPos);Position.assert(targetFromPos);Position.assert(targetToPos);var targetComparison=comparePos(targetFromPos,targetToPos);if(targetComparison===0){return sourceFromPos}if(targetComparison<0){var sourceCursor=sourceLines.skipSpaces(sourceFromPos);var targetCursor=targetLines.skipSpaces(targetFromPos);var lineDiff=targetToPos.line-targetCursor.line;sourceCursor.line+=lineDiff;targetCursor.line+=lineDiff;if(lineDiff>0){sourceCursor.column=0;targetCursor.column=0}else{assert.strictEqual(lineDiff,0)}while(comparePos(targetCursor,targetToPos)<0&&targetLines.nextPos(targetCursor,true)){assert.ok(sourceLines.nextPos(sourceCursor,true));assert.strictEqual(sourceLines.charAt(sourceCursor),targetLines.charAt(targetCursor))}}else{var sourceCursor=sourceLines.skipSpaces(sourceFromPos,true);var targetCursor=targetLines.skipSpaces(targetFromPos,true);var lineDiff=targetToPos.line-targetCursor.line;sourceCursor.line+=lineDiff;targetCursor.line+=lineDiff;if(lineDiff<0){sourceCursor.column=sourceLines.getLineLength(sourceCursor.line);targetCursor.column=targetLines.getLineLength(targetCursor.line)}else{assert.strictEqual(lineDiff,0)}while(comparePos(targetToPos,targetCursor)<0&&targetLines.prevPos(targetCursor,true)){assert.ok(sourceLines.prevPos(sourceCursor,true));assert.strictEqual(sourceLines.charAt(sourceCursor),targetLines.charAt(targetCursor))}}return sourceCursor}},{"./lines":146,"./types":152,"./util":153,assert:90}],148:[function(require,module,exports){var defaults={esprima:require("esprima-fb"),tabWidth:4,useTabs:false,reuseWhitespace:true,wrapColumn:74,sourceFileName:null,sourceMapName:null,sourceRoot:null,inputSourceMap:null,range:false,tolerant:true},hasOwn=defaults.hasOwnProperty;exports.normalize=function(options){options=options||defaults;function get(key){return hasOwn.call(options,key)?options[key]:defaults[key]}return{tabWidth:+get("tabWidth"),useTabs:!!get("useTabs"),reuseWhitespace:!!get("reuseWhitespace"),wrapColumn:Math.max(get("wrapColumn"),0),sourceFileName:get("sourceFileName"),sourceMapName:get("sourceMapName"),sourceRoot:get("sourceRoot"),inputSourceMap:get("inputSourceMap"),esprima:get("esprima"),range:get("range"),tolerant:get("tolerant")}}},{"esprima-fb":144}],149:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isObject=types.builtInTypes.object;var isArray=types.builtInTypes.array;var isFunction=types.builtInTypes.function;var Patcher=require("./patcher").Patcher;var normalizeOptions=require("./options").normalize;var fromString=require("./lines").fromString;var attachComments=require("./comments").attach;exports.parse=function parse(source,options){options=normalizeOptions(options);var lines=fromString(source,options);var sourceWithoutTabs=lines.toString({tabWidth:options.tabWidth,reuseWhitespace:false,useTabs:false});var program=options.esprima.parse(sourceWithoutTabs,{loc:true,range:options.range,comment:true,tolerant:options.tolerant});var comments=program.comments;delete program.comments;var file=b.file(program);file.loc={lines:lines,indent:0,start:lines.firstPos(),end:lines.lastPos()};var copy=new TreeCopier(lines).copy(file);attachComments(comments,copy.program,lines);return copy};function TreeCopier(lines){assert.ok(this instanceof TreeCopier);this.lines=lines;this.indent=0}var TCp=TreeCopier.prototype;TCp.copy=function(node){if(isArray.check(node)){return node.map(this.copy,this)}if(!isObject.check(node)){return node}if(n.MethodDefinition&&n.MethodDefinition.check(node)||n.Property.check(node)&&(node.method||node.shorthand)){node.value.loc=null;if(n.FunctionExpression.check(node.value)){node.value.id=null}}var copy=Object.create(Object.getPrototypeOf(node),{original:{value:node,configurable:false,enumerable:false,writable:true}});var loc=node.loc;var oldIndent=this.indent;var newIndent=oldIndent;if(loc){if(loc.start.line<1){loc.start.line=1}if(loc.end.line<1){loc.end.line=1}if(this.lines.isPrecededOnlyByWhitespace(loc.start)){newIndent=this.indent=loc.start.column}loc.lines=this.lines;loc.indent=newIndent}var keys=Object.keys(node);var keyCount=keys.length;for(var i=0;i<keyCount;++i){var key=keys[i];if(key==="loc"){copy[key]=node[key]}else if(key==="comments"){}else{copy[key]=this.copy(node[key])}}this.indent=oldIndent;if(node.comments){Object.defineProperty(copy,"comments",{value:node.comments,enumerable:false})}return copy}},{"./comments":145,"./lines":146,"./options":148,"./patcher":150,"./types":152,assert:90}],150:[function(require,module,exports){var assert=require("assert");var linesModule=require("./lines");var types=require("./types");var getFieldValue=types.getFieldValue;var Node=types.namedTypes.Node;var Expression=types.namedTypes.Expression;var SourceLocation=types.namedTypes.SourceLocation;var util=require("./util");var comparePos=util.comparePos;var NodePath=types.NodePath;var isObject=types.builtInTypes.object;var isArray=types.builtInTypes.array;var isString=types.builtInTypes.string;function Patcher(lines){assert.ok(this instanceof Patcher);assert.ok(lines instanceof linesModule.Lines);var self=this,replacements=[];self.replace=function(loc,lines){if(isString.check(lines))lines=linesModule.fromString(lines);replacements.push({lines:lines,start:loc.start,end:loc.end})};self.get=function(loc){loc=loc||{start:{line:1,column:0},end:{line:lines.length,column:lines.getLineLength(lines.length)}};var sliceFrom=loc.start,toConcat=[];function pushSlice(from,to){assert.ok(comparePos(from,to)<=0);toConcat.push(lines.slice(from,to))}replacements.sort(function(a,b){return comparePos(a.start,b.start)}).forEach(function(rep){if(comparePos(sliceFrom,rep.start)>0){}else{pushSlice(sliceFrom,rep.start);toConcat.push(rep.lines);sliceFrom=rep.end}});pushSlice(sliceFrom,loc.end);return linesModule.concat(toConcat)}}exports.Patcher=Patcher;exports.getReprinter=function(path){assert.ok(path instanceof NodePath);var node=path.value;if(!Node.check(node))return;var orig=node.original;var origLoc=orig&&orig.loc;var lines=origLoc&&origLoc.lines;var reprints=[];if(!lines||!findReprints(path,reprints))return;return function(print){var patcher=new Patcher(lines);reprints.forEach(function(reprint){var old=reprint.oldPath.value;SourceLocation.assert(old.loc,true);patcher.replace(old.loc,print(reprint.newPath).indentTail(old.loc.indent))});return patcher.get(origLoc).indentTail(-orig.loc.indent)}};function findReprints(newPath,reprints){var newNode=newPath.value;Node.assert(newNode);var oldNode=newNode.original;Node.assert(oldNode);assert.deepEqual(reprints,[]);if(newNode.type!==oldNode.type){return false}var oldPath=new NodePath(oldNode);var canReprint=findChildReprints(newPath,oldPath,reprints);if(!canReprint){reprints.length=0}return canReprint}function findAnyReprints(newPath,oldPath,reprints){var newNode=newPath.value;var oldNode=oldPath.value;if(newNode===oldNode)return true;if(isArray.check(newNode))return findArrayReprints(newPath,oldPath,reprints);if(isObject.check(newNode))return findObjectReprints(newPath,oldPath,reprints);return false}function findArrayReprints(newPath,oldPath,reprints){var newNode=newPath.value;var oldNode=oldPath.value;isArray.assert(newNode);var len=newNode.length;if(!(isArray.check(oldNode)&&oldNode.length===len))return false;for(var i=0;i<len;++i)if(!findAnyReprints(newPath.get(i),oldPath.get(i),reprints))return false;return true}function findObjectReprints(newPath,oldPath,reprints){var newNode=newPath.value;isObject.assert(newNode);if(newNode.original===null){return false}var oldNode=oldPath.value;if(!isObject.check(oldNode))return false;if(Node.check(newNode)){if(!Node.check(oldNode)){return false}if(!oldNode.loc){return false}if(newNode.type===oldNode.type){var childReprints=[];if(findChildReprints(newPath,oldPath,childReprints)){reprints.push.apply(reprints,childReprints)}else{reprints.push({newPath:newPath,oldPath:oldPath})}return true}if(Expression.check(newNode)&&Expression.check(oldNode)){reprints.push({newPath:newPath,oldPath:oldPath});return true}return false}return findChildReprints(newPath,oldPath,reprints)}var reusablePos={line:1,column:0};function hasOpeningParen(oldPath){var oldNode=oldPath.value;var loc=oldNode.loc;var lines=loc&&loc.lines;if(lines){var pos=reusablePos;pos.line=loc.start.line;pos.column=loc.start.column;while(lines.prevPos(pos)){var ch=lines.charAt(pos);if(ch==="("){var rootPath=oldPath;while(rootPath.parentPath)rootPath=rootPath.parentPath;return comparePos(rootPath.value.loc.start,pos)<=0}if(ch!==" "){return false}}}return false}function hasClosingParen(oldPath){var oldNode=oldPath.value;var loc=oldNode.loc;var lines=loc&&loc.lines;if(lines){var pos=reusablePos;pos.line=loc.end.line;pos.column=loc.end.column;do{var ch=lines.charAt(pos);if(ch===")"){var rootPath=oldPath;while(rootPath.parentPath)rootPath=rootPath.parentPath;return comparePos(pos,rootPath.value.loc.end)<=0}if(ch!==" "){return false}}while(lines.nextPos(pos))}return false}function hasParens(oldPath){return hasOpeningParen(oldPath)&&hasClosingParen(oldPath)}function findChildReprints(newPath,oldPath,reprints){var newNode=newPath.value;var oldNode=oldPath.value;isObject.assert(newNode);isObject.assert(oldNode);if(newNode.original===null){return false}if(!newPath.canBeFirstInStatement()&&newPath.firstInStatement()&&!hasOpeningParen(oldPath))return false;if(newPath.needsParens(true)&&!hasParens(oldPath)){return false}for(var k in util.getUnionOfKeys(newNode,oldNode)){if(k==="loc")continue;if(!findAnyReprints(newPath.get(k),oldPath.get(k),reprints))return false}return true}},{"./lines":146,"./types":152,"./util":153,assert:90}],151:[function(require,module,exports){var assert=require("assert");var sourceMap=require("source-map");var printComments=require("./comments").printComments;var linesModule=require("./lines");var fromString=linesModule.fromString;var concat=linesModule.concat;var normalizeOptions=require("./options").normalize;var getReprinter=require("./patcher").getReprinter;var types=require("./types");var namedTypes=types.namedTypes;var isString=types.builtInTypes.string;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var util=require("./util");function PrintResult(code,sourceMap){assert.ok(this instanceof PrintResult);isString.assert(code);this.code=code;if(sourceMap){isObject.assert(sourceMap);this.map=sourceMap}}var PRp=PrintResult.prototype;var warnedAboutToString=false;PRp.toString=function(){if(!warnedAboutToString){console.warn("Deprecation warning: recast.print now returns an object with "+"a .code property. You appear to be treating the object as a "+"string, which might still work but is strongly discouraged.");warnedAboutToString=true}return this.code};var emptyPrintResult=new PrintResult("");function Printer(originalOptions){assert.ok(this instanceof Printer);var explicitTabWidth=originalOptions&&originalOptions.tabWidth;var options=normalizeOptions(originalOptions);assert.notStrictEqual(options,originalOptions);options.sourceFileName=null;function printWithComments(path){assert.ok(path instanceof NodePath);return printComments(path.node.comments,print(path),options)}function print(path,includeComments){if(includeComments)return printWithComments(path);assert.ok(path instanceof NodePath);if(!explicitTabWidth){var oldTabWidth=options.tabWidth;var loc=path.node.loc;if(loc&&loc.lines&&loc.lines.guessTabWidth){options.tabWidth=loc.lines.guessTabWidth();var lines=maybeReprint(path);options.tabWidth=oldTabWidth;return lines}}return maybeReprint(path)}function maybeReprint(path){var reprinter=getReprinter(path);if(reprinter)return maybeAddParens(path,reprinter(maybeReprint));return printRootGenerically(path)}function printRootGenerically(path){return genericPrint(path,options,printWithComments)}function printGenerically(path){return genericPrint(path,options,printGenerically)}this.print=function(ast){if(!ast){return emptyPrintResult}var path=ast instanceof NodePath?ast:new NodePath(ast);var lines=print(path,true);return new PrintResult(lines.toString(options),util.composeSourceMaps(options.inputSourceMap,lines.getSourceMap(options.sourceMapName,options.sourceRoot)))};this.printGenerically=function(ast){if(!ast){return emptyPrintResult}var path=ast instanceof NodePath?ast:new NodePath(ast);var oldReuseWhitespace=options.reuseWhitespace;options.reuseWhitespace=false;var pr=new PrintResult(printGenerically(path).toString(options));options.reuseWhitespace=oldReuseWhitespace;return pr}}exports.Printer=Printer;function maybeAddParens(path,lines){return path.needsParens()?concat(["(",lines,")"]):lines}function genericPrint(path,options,printPath){assert.ok(path instanceof NodePath);return maybeAddParens(path,genericPrintNoParens(path,options,printPath))}function genericPrintNoParens(path,options,print){var n=path.value;if(!n){return fromString("")}if(typeof n==="string"){return fromString(n,options)}namedTypes.Node.assert(n);switch(n.type){case"File":path=path.get("program");n=path.node;namedTypes.Program.assert(n);case"Program":return maybeAddSemicolon(printStatementSequence(path.get("body"),options,print));case"EmptyStatement":return fromString("");case"ExpressionStatement":return concat([print(path.get("expression")),";"]);case"BinaryExpression":case"LogicalExpression":case"AssignmentExpression":return fromString(" ").join([print(path.get("left")),n.operator,print(path.get("right"))]);case"MemberExpression":var parts=[print(path.get("object"))];if(n.computed)parts.push("[",print(path.get("property")),"]");else parts.push(".",print(path.get("property")));return concat(parts);case"Path":return fromString(".").join(n.body);case"Identifier":return fromString(n.name,options);case"SpreadElement":case"SpreadElementPattern":case"SpreadProperty":case"SpreadPropertyPattern":return concat(["...",print(path.get("argument"))]);case"FunctionDeclaration":case"FunctionExpression":var parts=[];if(n.async)parts.push("async ");parts.push("function");if(n.generator)parts.push("*");if(n.id)parts.push(" ",print(path.get("id")));parts.push("(",printFunctionParams(path,options,print),") ",print(path.get("body")));return concat(parts);case"ArrowFunctionExpression":var parts=[];if(n.async)parts.push("async ");if(n.params.length===1){parts.push(print(path.get("params",0)))}else{parts.push("(",printFunctionParams(path,options,print),")")}parts.push(" => ",print(path.get("body")));return concat(parts);case"MethodDefinition":var parts=[];if(n.static){parts.push("static ")}parts.push(printMethod(n.kind,path.get("key"),path.get("value"),options,print));return concat(parts);case"YieldExpression":var parts=["yield"];if(n.delegate)parts.push("*");if(n.argument)parts.push(" ",print(path.get("argument")));return concat(parts);case"AwaitExpression":var parts=["await"];if(n.all)parts.push("*");if(n.argument)parts.push(" ",print(path.get("argument")));return concat(parts);case"ModuleDeclaration":var parts=["module",print(path.get("id"))];if(n.source){assert.ok(!n.body);parts.push("from",print(path.get("source")))}else{parts.push(print(path.get("body")))}return fromString(" ").join(parts);case"ImportSpecifier":case"ExportSpecifier":var parts=[print(path.get("id"))];if(n.name)parts.push(" as ",print(path.get("name")));return concat(parts);case"ExportBatchSpecifier":return fromString("*");case"ImportNamespaceSpecifier":return concat(["* as ",print(path.get("id"))]);case"ImportDefaultSpecifier":return print(path.get("id"));case"ExportDeclaration":var parts=["export"];if(n["default"]){parts.push(" default")}else if(n.specifiers&&n.specifiers.length>0){if(n.specifiers.length===1&&n.specifiers[0].type==="ExportBatchSpecifier"){parts.push(" *")}else{parts.push(" { ",fromString(", ").join(path.get("specifiers").map(print))," }")}if(n.source)parts.push(" from ",print(path.get("source")));parts.push(";");return concat(parts)}if(n.declaration){if(!namedTypes.Node.check(n.declaration)){console.log(JSON.stringify(n,null,2))}var decLines=print(path.get("declaration"));parts.push(" ",decLines);if(lastNonSpaceCharacter(decLines)!==";"){parts.push(";")}}return concat(parts);case"ImportDeclaration":var parts=["import "];if(n.specifiers&&n.specifiers.length>0){var foundImportSpecifier=false;path.get("specifiers").each(function(sp){if(sp.name>0){parts.push(", ")}if(namedTypes.ImportDefaultSpecifier.check(sp.value)||namedTypes.ImportNamespaceSpecifier.check(sp.value)){assert.strictEqual(foundImportSpecifier,false)}else{namedTypes.ImportSpecifier.assert(sp.value);if(!foundImportSpecifier){foundImportSpecifier=true;parts.push("{")}}parts.push(print(sp))});if(foundImportSpecifier){parts.push("}")}parts.push(" from ")}parts.push(print(path.get("source")),";");return concat(parts);case"BlockStatement":var naked=printStatementSequence(path.get("body"),options,print);if(naked.isEmpty())return fromString("{}");return concat(["{\n",naked.indent(options.tabWidth),"\n}"]);case"ReturnStatement":var parts=["return"];if(n.argument){var argLines=print(path.get("argument"));if(argLines.length>1&&namedTypes.XJSElement&&namedTypes.XJSElement.check(n.argument)){parts.push(" (\n",argLines.indent(options.tabWidth),"\n)")}else{parts.push(" ",argLines)}}parts.push(";");return concat(parts);case"CallExpression":return concat([print(path.get("callee")),printArgumentsList(path,options,print)]);case"ObjectExpression":case"ObjectPattern":var allowBreak=false,len=n.properties.length,parts=[len>0?"{\n":"{"];path.get("properties").map(function(childPath){var prop=childPath.value;var i=childPath.name;var lines=print(childPath).indent(options.tabWidth);var multiLine=lines.length>1;if(multiLine&&allowBreak){parts.push("\n")}parts.push(lines);if(i<len-1){parts.push(multiLine?",\n\n":",\n");allowBreak=!multiLine}});parts.push(len>0?"\n}":"}");return concat(parts);case"PropertyPattern":return concat([print(path.get("key")),": ",print(path.get("pattern"))]);case"Property":if(n.method||n.kind==="get"||n.kind==="set"){return printMethod(n.kind,path.get("key"),path.get("value"),options,print)}if(path.node.shorthand){return print(path.get("key"))}else{return concat([print(path.get("key")),": ",print(path.get("value"))])}case"ArrayExpression":case"ArrayPattern":var elems=n.elements,len=elems.length,parts=["["];path.get("elements").each(function(elemPath){var elem=elemPath.value;if(!elem){parts.push(",")}else{var i=elemPath.name;if(i>0)parts.push(" ");parts.push(print(elemPath));if(i<len-1)parts.push(",")}});parts.push("]");return concat(parts);case"SequenceExpression":return fromString(", ").join(path.get("expressions").map(print));case"ThisExpression":return fromString("this");case"Literal":if(typeof n.value!=="string")return fromString(n.value,options);case"ModuleSpecifier":return fromString(nodeStr(n),options);case"UnaryExpression":var parts=[n.operator];if(/[a-z]$/.test(n.operator))parts.push(" ");parts.push(print(path.get("argument")));return concat(parts);case"UpdateExpression":var parts=[print(path.get("argument")),n.operator];if(n.prefix)parts.reverse();return concat(parts);case"ConditionalExpression":return concat(["(",print(path.get("test"))," ? ",print(path.get("consequent"))," : ",print(path.get("alternate")),")"]);case"NewExpression":var parts=["new ",print(path.get("callee"))];var args=n.arguments;if(args){parts.push(printArgumentsList(path,options,print))}return concat(parts);case"VariableDeclaration":var parts=[n.kind," "];var maxLen=0;var printed=path.get("declarations").map(function(childPath){var lines=print(childPath);maxLen=Math.max(lines.length,maxLen);return lines});if(maxLen===1){parts.push(fromString(", ").join(printed))}else if(printed.length>1){parts.push(fromString(",\n").join(printed).indentTail(n.kind.length+1))}else{parts.push(printed[0])}var parentNode=path.parent&&path.parent.node;if(!namedTypes.ForStatement.check(parentNode)&&!namedTypes.ForInStatement.check(parentNode)&&!(namedTypes.ForOfStatement&&namedTypes.ForOfStatement.check(parentNode))){parts.push(";")}return concat(parts);case"VariableDeclarator":return n.init?fromString(" = ").join([print(path.get("id")),print(path.get("init"))]):print(path.get("id"));case"WithStatement":return concat(["with (",print(path.get("object")),") ",print(path.get("body"))]);case"IfStatement":var con=adjustClause(print(path.get("consequent")),options),parts=["if (",print(path.get("test")),")",con];if(n.alternate)parts.push(endsWithBrace(con)?" else":"\nelse",adjustClause(print(path.get("alternate")),options));return concat(parts);case"ForStatement":var init=print(path.get("init")),sep=init.length>1?";\n":"; ",forParen="for (",indented=fromString(sep).join([init,print(path.get("test")),print(path.get("update"))]).indentTail(forParen.length),head=concat([forParen,indented,")"]),clause=adjustClause(print(path.get("body")),options),parts=[head];if(head.length>1){parts.push("\n");clause=clause.trimLeft()}parts.push(clause);return concat(parts);case"WhileStatement":return concat(["while (",print(path.get("test")),")",adjustClause(print(path.get("body")),options)]);case"ForInStatement":return concat([n.each?"for each (":"for (",print(path.get("left"))," in ",print(path.get("right")),")",adjustClause(print(path.get("body")),options)]);case"ForOfStatement":return concat(["for (",print(path.get("left"))," of ",print(path.get("right")),")",adjustClause(print(path.get("body")),options)]);
case"DoWhileStatement":var doBody=concat(["do",adjustClause(print(path.get("body")),options)]),parts=[doBody];if(endsWithBrace(doBody))parts.push(" while");else parts.push("\nwhile");parts.push(" (",print(path.get("test")),");");return concat(parts);case"BreakStatement":var parts=["break"];if(n.label)parts.push(" ",print(path.get("label")));parts.push(";");return concat(parts);case"ContinueStatement":var parts=["continue"];if(n.label)parts.push(" ",print(path.get("label")));parts.push(";");return concat(parts);case"LabeledStatement":return concat([print(path.get("label")),":\n",print(path.get("body"))]);case"TryStatement":var parts=["try ",print(path.get("block"))];path.get("handlers").each(function(handler){parts.push(" ",print(handler))});if(n.finalizer)parts.push(" finally ",print(path.get("finalizer")));return concat(parts);case"CatchClause":var parts=["catch (",print(path.get("param"))];if(n.guard)parts.push(" if ",print(path.get("guard")));parts.push(") ",print(path.get("body")));return concat(parts);case"ThrowStatement":return concat(["throw ",print(path.get("argument")),";"]);case"SwitchStatement":return concat(["switch (",print(path.get("discriminant")),") {\n",fromString("\n").join(path.get("cases").map(print)),"\n}"]);case"SwitchCase":var parts=[];if(n.test)parts.push("case ",print(path.get("test")),":");else parts.push("default:");if(n.consequent.length>0){parts.push("\n",printStatementSequence(path.get("consequent"),options,print).indent(options.tabWidth))}return concat(parts);case"DebuggerStatement":return fromString("debugger;");case"XJSAttribute":var parts=[print(path.get("name"))];if(n.value)parts.push("=",print(path.get("value")));return concat(parts);case"XJSIdentifier":return fromString(n.name,options);case"XJSNamespacedName":return fromString(":").join([print(path.get("namespace")),print(path.get("name"))]);case"XJSMemberExpression":return fromString(".").join([print(path.get("object")),print(path.get("property"))]);case"XJSSpreadAttribute":return concat(["{...",print(path.get("argument")),"}"]);case"XJSExpressionContainer":return concat(["{",print(path.get("expression")),"}"]);case"XJSElement":var openingLines=print(path.get("openingElement"));if(n.openingElement.selfClosing){assert.ok(!n.closingElement);return openingLines}var childLines=concat(path.get("children").map(function(childPath){var child=childPath.value;if(namedTypes.Literal.check(child)&&typeof child.value==="string"){if(/\S/.test(child.value)){return child.value.replace(/^\s+|\s+$/g,"")}else if(/\n/.test(child.value)){return"\n"}}return print(childPath)})).indentTail(options.tabWidth);var closingLines=print(path.get("closingElement"));return concat([openingLines,childLines,closingLines]);case"XJSOpeningElement":var parts=["<",print(path.get("name"))];var attrParts=[];path.get("attributes").each(function(attrPath){attrParts.push(" ",print(attrPath))});var attrLines=concat(attrParts);var needLineWrap=attrLines.length>1||attrLines.getLineLength(1)>options.wrapColumn;if(needLineWrap){attrParts.forEach(function(part,i){if(part===" "){assert.strictEqual(i%2,0);attrParts[i]="\n"}});attrLines=concat(attrParts).indentTail(options.tabWidth)}parts.push(attrLines,n.selfClosing?" />":">");return concat(parts);case"XJSClosingElement":return concat(["</",print(path.get("name")),">"]);case"XJSText":return fromString(n.value,options);case"XJSEmptyExpression":return fromString("");case"TypeAnnotatedIdentifier":var parts=[print(path.get("annotation"))," ",print(path.get("identifier"))];return concat(parts);case"ClassBody":if(n.body.length===0){return fromString("{}")}return concat(["{\n",printStatementSequence(path.get("body"),options,print).indent(options.tabWidth),"\n}"]);case"ClassPropertyDefinition":var parts=["static ",print(path.get("definition"))];if(!namedTypes.MethodDefinition.check(n.definition))parts.push(";");return concat(parts);case"ClassProperty":return concat([print(path.get("id")),";"]);case"ClassDeclaration":case"ClassExpression":var parts=["class"];if(n.id)parts.push(" ",print(path.get("id")));if(n.superClass)parts.push(" extends ",print(path.get("superClass")));parts.push(" ",print(path.get("body")));return concat(parts);case"Node":case"Printable":case"SourceLocation":case"Position":case"Statement":case"Function":case"Pattern":case"Expression":case"Declaration":case"Specifier":case"NamedSpecifier":case"Block":case"Line":throw new Error("unprintable type: "+JSON.stringify(n.type));case"ClassHeritage":case"ComprehensionBlock":case"ComprehensionExpression":case"Glob":case"TaggedTemplateExpression":case"TemplateElement":case"TemplateLiteral":case"GeneratorExpression":case"LetStatement":case"LetExpression":case"GraphExpression":case"GraphIndexExpression":case"AnyTypeAnnotation":case"BooleanTypeAnnotation":case"ClassImplements":case"DeclareClass":case"DeclareFunction":case"DeclareModule":case"DeclareVariable":case"FunctionTypeAnnotation":case"FunctionTypeParam":case"GenericTypeAnnotation":case"InterfaceDeclaration":case"InterfaceExtends":case"IntersectionTypeAnnotation":case"MemberTypeAnnotation":case"NullableTypeAnnotation":case"NumberTypeAnnotation":case"ObjectTypeAnnotation":case"ObjectTypeCallProperty":case"ObjectTypeIndexer":case"ObjectTypeProperty":case"QualifiedTypeIdentifier":case"StringLiteralTypeAnnotation":case"StringTypeAnnotation":case"TupleTypeAnnotation":case"Type":case"TypeAlias":case"TypeAnnotation":case"TypeParameterDeclaration":case"TypeParameterInstantiation":case"TypeofTypeAnnotation":case"UnionTypeAnnotation":case"VoidTypeAnnotation":case"XMLDefaultDeclaration":case"XMLAnyName":case"XMLQualifiedIdentifier":case"XMLFunctionQualifiedIdentifier":case"XMLAttributeSelector":case"XMLFilterExpression":case"XML":case"XMLElement":case"XMLList":case"XMLEscape":case"XMLText":case"XMLStartTag":case"XMLEndTag":case"XMLPointTag":case"XMLName":case"XMLAttribute":case"XMLCdata":case"XMLComment":case"XMLProcessingInstruction":default:debugger;throw new Error("unknown type: "+JSON.stringify(n.type))}return p}function printStatementSequence(path,options,print){var inClassBody=path.parent&&namedTypes.ClassBody&&namedTypes.ClassBody.check(path.parent.node);var filtered=path.filter(function(stmtPath){var stmt=stmtPath.value;if(!stmt)return false;if(stmt.type==="EmptyStatement")return false;if(!inClassBody){namedTypes.Statement.assert(stmt)}return true});var prevTrailingSpace=null;var len=filtered.length;var parts=[];filtered.forEach(function(stmtPath,i){var printed=print(stmtPath);var stmt=stmtPath.value;var needSemicolon=true;var multiLine=printed.length>1;var notFirst=i>0;var notLast=i<len-1;var leadingSpace;var trailingSpace;if(inClassBody){var stmt=stmtPath.value;if(namedTypes.MethodDefinition.check(stmt)||namedTypes.ClassPropertyDefinition.check(stmt)&&namedTypes.MethodDefinition.check(stmt.definition)){needSemicolon=false}}if(needSemicolon){printed=maybeAddSemicolon(printed)}var trueLoc=options.reuseWhitespace&&getTrueLoc(stmt);var lines=trueLoc&&trueLoc.lines;if(notFirst){if(lines){var beforeStart=lines.skipSpaces(trueLoc.start,true);var beforeStartLine=beforeStart?beforeStart.line:1;var leadingGap=trueLoc.start.line-beforeStartLine;leadingSpace=Array(leadingGap+1).join("\n")}else{leadingSpace=multiLine?"\n\n":"\n"}}else{leadingSpace=""}if(notLast){if(lines){var afterEnd=lines.skipSpaces(trueLoc.end);var afterEndLine=afterEnd?afterEnd.line:lines.length;var trailingGap=afterEndLine-trueLoc.end.line;trailingSpace=Array(trailingGap+1).join("\n")}else{trailingSpace=multiLine?"\n\n":"\n"}}else{trailingSpace=""}parts.push(maxSpace(prevTrailingSpace,leadingSpace),printed);if(notLast){prevTrailingSpace=trailingSpace}else if(trailingSpace){parts.push(trailingSpace)}});return concat(parts)}function getTrueLoc(node){if(!node.loc){return null}if(!node.comments){return node.loc}var start=node.loc.start;var end=node.loc.end;node.comments.forEach(function(comment){if(comment.loc){if(util.comparePos(comment.loc.start,start)<0){start=comment.loc.start}if(util.comparePos(end,comment.loc.end)<0){end=comment.loc.end}}});return{lines:node.loc.lines,start:start,end:end}}function maxSpace(s1,s2){if(!s1&&!s2){return fromString("")}if(!s1){return fromString(s2)}if(!s2){return fromString(s1)}var spaceLines1=fromString(s1);var spaceLines2=fromString(s2);if(spaceLines2.length>spaceLines1.length){return spaceLines2}return spaceLines1}function printMethod(kind,keyPath,valuePath,options,print){var parts=[];var key=keyPath.value;var value=valuePath.value;namedTypes.FunctionExpression.assert(value);if(value.async){parts.push("async ")}if(!kind||kind==="init"){if(value.generator){parts.push("*")}}else{assert.ok(kind==="get"||kind==="set");parts.push(kind," ")}parts.push(print(keyPath),"(",printFunctionParams(valuePath,options,print),") ",print(valuePath.get("body")));return concat(parts)}function printArgumentsList(path,options,print){var printed=path.get("arguments").map(print);var joined=fromString(", ").join(printed);if(joined.getLineLength(1)>options.wrapColumn){joined=fromString(",\n").join(printed);return concat(["(\n",joined.indent(options.tabWidth),"\n)"])}return concat(["(",joined,")"])}function printFunctionParams(path,options,print){var fun=path.node;namedTypes.Function.assert(fun);var params=path.get("params");var defaults=path.get("defaults");var printed=params.map(defaults.value?function(param){var p=print(param);var d=defaults.get(param.name);return d.value?concat([p,"=",print(d)]):p}:print);if(fun.rest){printed.push(concat(["...",print(path.get("rest"))]))}var joined=fromString(", ").join(printed);if(joined.length>1||joined.getLineLength(1)>options.wrapColumn){joined=fromString(",\n").join(printed);return concat(["\n",joined.indent(options.tabWidth)])}return joined}function adjustClause(clause,options){if(clause.length>1)return concat([" ",clause]);return concat(["\n",maybeAddSemicolon(clause).indent(options.tabWidth)])}function lastNonSpaceCharacter(lines){var pos=lines.lastPos();do{var ch=lines.charAt(pos);if(/\S/.test(ch))return ch}while(lines.prevPos(pos))}function endsWithBrace(lines){return lastNonSpaceCharacter(lines)==="}"}function nodeStr(n){namedTypes.Literal.assert(n);isString.assert(n.value);return JSON.stringify(n.value)}function maybeAddSemicolon(lines){var eoc=lastNonSpaceCharacter(lines);if(!eoc||"\n};".indexOf(eoc)<0)return concat([lines,";"]);return lines}},{"./comments":145,"./lines":146,"./options":148,"./patcher":150,"./types":152,"./util":153,assert:90,"source-map":163}],152:[function(require,module,exports){var types=require("ast-types");var def=types.Type.def;def("File").bases("Node").build("program").field("program",def("Program"));types.finalize();module.exports=types},{"ast-types":88}],153:[function(require,module,exports){var assert=require("assert");var getFieldValue=require("./types").getFieldValue;var sourceMap=require("source-map");var SourceMapConsumer=sourceMap.SourceMapConsumer;var SourceMapGenerator=sourceMap.SourceMapGenerator;var hasOwn=Object.prototype.hasOwnProperty;function getUnionOfKeys(){var result={};var argc=arguments.length;for(var i=0;i<argc;++i){var keys=Object.keys(arguments[i]);var keyCount=keys.length;for(var j=0;j<keyCount;++j){result[keys[j]]=true}}return result}exports.getUnionOfKeys=getUnionOfKeys;function comparePos(pos1,pos2){return pos1.line-pos2.line||pos1.column-pos2.column}exports.comparePos=comparePos;exports.composeSourceMaps=function(formerMap,latterMap){if(formerMap){if(!latterMap){return formerMap}}else{return latterMap||null}var smcFormer=new SourceMapConsumer(formerMap);var smcLatter=new SourceMapConsumer(latterMap);var smg=new SourceMapGenerator({file:latterMap.file,sourceRoot:latterMap.sourceRoot});var sourcesToContents={};smcLatter.eachMapping(function(mapping){var origPos=smcFormer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});var sourceName=origPos.source;if(sourceName===null){return}smg.addMapping({source:sourceName,original:{line:origPos.line,column:origPos.column},generated:{line:mapping.generatedLine,column:mapping.generatedColumn},name:mapping.name});var sourceContent=smcFormer.sourceContentFor(sourceName);if(sourceContent&&!hasOwn.call(sourcesToContents,sourceName)){sourcesToContents[sourceName]=sourceContent;smg.setSourceContent(sourceName,sourceContent)}});return smg.toJSON()}},{"./types":152,assert:90,"source-map":163}],154:[function(require,module,exports){(function(process){var types=require("./lib/types");var parse=require("./lib/parser").parse;var Printer=require("./lib/printer").Printer;function print(node,options){return new Printer(options).print(node)}function prettyPrint(node,options){return new Printer(options).printGenerically(node)}function run(transformer,options){return runFile(process.argv[2],transformer,options)}function runFile(path,transformer,options){require("fs").readFile(path,"utf-8",function(err,code){if(err){console.error(err);return}runString(code,transformer,options)})}function defaultWriteback(output){process.stdout.write(output)}function runString(code,transformer,options){var writeback=options&&options.writeback||defaultWriteback;transformer(parse(code,options),function(node){writeback(print(node,options).code)})}Object.defineProperties(exports,{parse:{enumerable:true,value:parse},visit:{enumerable:true,value:types.visit},print:{enumerable:true,value:print},prettyPrint:{enumerable:false,value:prettyPrint},types:{enumerable:false,value:types},run:{enumerable:false,value:run}})}).call(this,require("_process"))},{"./lib/parser":149,"./lib/printer":151,"./lib/types":152,_process:99,fs:89}],155:[function(require,module,exports){(function(process){var Stream=require("stream");exports=module.exports=through;through.through=through;function through(write,end,opts){write=write||function(data){this.queue(data)};end=end||function(){this.queue(null)};var ended=false,destroyed=false,buffer=[],_ended=false;var stream=new Stream;stream.readable=stream.writable=true;stream.paused=false;stream.autoDestroy=!(opts&&opts.autoDestroy===false);stream.write=function(data){write.call(this,data);return!stream.paused};function drain(){while(buffer.length&&!stream.paused){var data=buffer.shift();if(null===data)return stream.emit("end");else stream.emit("data",data)}}stream.queue=stream.push=function(data){if(_ended)return stream;if(data==null)_ended=true;buffer.push(data);drain();return stream};stream.on("end",function(){stream.readable=false;if(!stream.writable&&stream.autoDestroy)process.nextTick(function(){stream.destroy()})});function _end(){stream.writable=false;end.call(stream);if(!stream.readable&&stream.autoDestroy)stream.destroy()}stream.end=function(data){if(ended)return;ended=true;if(arguments.length)stream.write(data);_end();return stream};stream.destroy=function(){if(destroyed)return;destroyed=true;ended=true;buffer.length=0;stream.writable=stream.readable=false;stream.emit("close");return stream};stream.pause=function(){if(stream.paused)return;stream.paused=true;return stream};stream.resume=function(){if(stream.paused){stream.paused=false;stream.emit("resume")}drain();if(!stream.paused)stream.emit("drain");return stream};return stream}}).call(this,require("_process"))},{_process:99,stream:111}],156:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1;function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next}return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{}],157:[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:159}],158:[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}},{}],159:[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:{})},{}],160:[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:{})},{}],161:[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&¤t("\\")&&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,})\}/))){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}})()},{}],162:[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":157,"./data/iu-mappings.json":158,regenerate:159,regjsgen:160,regjsparser:161}],163:[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":168,"./source-map/source-map-generator":169,"./source-map/source-node":170}],164:[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":171,amdefine:172}],165:[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":166,amdefine:172}],166:[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:172}],167:[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:172}],168:[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":164,"./base64-vlq":165,"./binary-search":167,"./util":171,amdefine:172}],169:[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":164,"./base64-vlq":165,"./util":171,amdefine:172}],170:[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":169,"./util":171,amdefine:172}],171:[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:172}],172:[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:99,path:98}],173:[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:"FunctionExpression",id:null,params:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"instance"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"prototype"},computed:false}]}}],kind:"var"},{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"result"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"Identifier",name:"instance"},{type:"Identifier",name:"args"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"Identifier",name:"result"},operator:"!=",right:{type:"Literal",value:null}},operator:"&&",right:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"object"}},operator:"||",right:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"function"}}}},consequent:{type:"Identifier",name:"result"},alternate:{type:"Identifier",name:"instance"}}}]},expression:false}}]},"array-comprehension-container":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false},arguments:[]}}]},"array-comprehension-for-each":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"forEach"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}]}}]},"array-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-super-constructor-call":{type:"Program",body:[{type:"IfStatement",test:{type:"Identifier",name:"SUPER_NAME"},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SUPER_NAME"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},alternate:null}]},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default-module-override":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"exports"},right:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}}]},"exports-default-module":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{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"}]}}]},"for-of":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"ITERATOR_KEY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"STEP_KEY"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"STEP_KEY"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ITERATOR_KEY"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[]}}]},"function-return-obj":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{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}]},inherits:{type:"Program",body:[{type:"ExpressionStatement",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:"LogicalExpression",left:{type:"Identifier",name:"parent"},operator:"&&",right:{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:"IfStatement",test:{type:"Identifier",name:"parent"},consequent:{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"}}},alternate:null}]},expression:false}}]},"interop-require":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"LogicalExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Literal",value:"default"},computed:true},operator:"||",right:{type:"Identifier",name:"obj"}}}}]},expression:false}}]},"let-scoping-return":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"RETURN"}},operator:"===",right:{type:"Literal",value:"object"}},consequent:{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"RETURN"},property:{type:"Identifier",name:"v"},computed:false}},alternate:null}]},"object-define-properties-closure":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{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-without-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"keys"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"ObjectExpression",properties:[]}}],kind:"var"},{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"keys"},property:{type:"Identifier",name:"indexOf"},computed:false},arguments:[{type:"Identifier",name:"i"}]},operator:">=",right:{type:"Literal",value:0}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"i"}]}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}]},"prototype-identifier":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"Identifier",name:"CLASS_NAME"},property:{type:"Identifier",name:"prototype"},computed:false}}]},"prototype-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"},{type:"Identifier",name:"instanceProps"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"staticProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"}]}},alternate:null},{type:"IfStatement",test:{type:"Identifier",name:"instanceProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"Identifier",name:"instanceProps"}]}},alternate:null}]},expression:false}}]},"require-assign-key":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]},property:{type:"Identifier",name:"KEY"},computed:false}}],kind:"var"}]},"require-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}}]},system:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"System"},property:{type:"Identifier",name:"register"},computed:false},arguments:[{type:"Identifier",name:"MODULE_NAME"},{type:"Identifier",name:"MODULE_DEPENDENCIES"},{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"EXPORT_IDENTIFIER"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"setters"},value:{type:"Identifier",name:"SETTERS"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"execute"},value:{type:"Identifier",name:"EXECUTE"},kind:"init"}]}}]},expression:false}]}}]},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"freeze"},computed:false},arguments:[{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"strings"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"raw"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"freeze"},computed:false},arguments:[{type:"Identifier",name:"raw"}]},kind:"init"}]},kind:"init"}]}]}]}}]},expression:false}}]},"to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"Identifier",name:"arr"},alternate:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"arr"}]}}}]},expression:false}}]},"umd-runner-body":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"factory"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"define"}},operator:"===",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"define"},property:{type:"Identifier",name:"amd"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"define"},arguments:[{type:"Identifier",name:"AMD_ARGUMENTS"},{type:"Identifier",name:"factory"}]}}]},alternate:{type:"IfStatement",test:{type:"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}}]}}},{}]},{},[2])(2)}); |
node_modules/react-bootstrap/src/PanelGroup.js | gitoneman/react-soc | import React, { cloneElement } from 'react';
import classSet from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import ValidComponentChildren from './utils/ValidComponentChildren';
const PanelGroup = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
collapsable: React.PropTypes.bool,
activeKey: React.PropTypes.any,
defaultActiveKey: React.PropTypes.any,
onSelect: React.PropTypes.func
},
getDefaultProps() {
return {
bsClass: 'panel-group'
};
},
getInitialState() {
let defaultActiveKey = this.props.defaultActiveKey;
return {
activeKey: defaultActiveKey
};
},
render() {
let classes = this.getBsClassSet();
return (
<div {...this.props} className={classSet(this.props.className, classes)} onSelect={null}>
{ValidComponentChildren.map(this.props.children, this.renderPanel)}
</div>
);
},
renderPanel(child, index) {
let activeKey =
this.props.activeKey != null ? this.props.activeKey : this.state.activeKey;
let props = {
bsStyle: child.props.bsStyle || this.props.bsStyle,
key: child.key ? child.key : index,
ref: child.ref
};
if (this.props.accordion) {
props.collapsable = true;
props.expanded = (child.props.eventKey === activeKey);
props.onSelect = this.handleSelect;
}
return cloneElement(
child,
props
);
},
shouldComponentUpdate() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
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
});
}
});
export default PanelGroup;
|
__tests__/components/SkipLinks-test.js | odedre/grommet-final | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React from 'react';
import renderer from 'react-test-renderer';
import SkipLinks from '../../src/js/components/SkipLinks';
// needed because this:
// https://github.com/facebook/jest/issues/1353
jest.mock('react-dom');
describe('SkipLinks', () => {
it('has correct default options', () => {
const component = renderer.create(
<SkipLinks />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
js/components/DeviceTypes/MethodType.js | gilesbradshaw/uaQL | // @flow
'use strict';
import React from 'react';
import Relay from 'react-relay';
import {createContainer} from 'recompose-relay';
import {compose, doOnReceiveProps} from 'recompose';
import DataValue from '../DataValue';
const composer = compose(
createContainer(
{
fragments: {
viewer: () => Relay.QL`
fragment on UANode {
id
displayName {
text
}
}
`
}
}
)
);
const MethodType = composer
(({viewer})=>
<div> METHOD!! {viewer.displayName.text}
</div>
);
const Svg = composer(()=><g/>);
export {MethodType as default, Svg};
|
executor/htdocs/lib/jquery-1.8.0.min.js | owulveryck/gorchestrator | /*! jQuery [email protected] jquery.com | jquery.org/license */
(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.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%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},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(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.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(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={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,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[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","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); |
src/client/containers/Auth/Login.js | eliasmeire/hz-pictionary | import React from 'react';
import { Button, Heading } from 'grommet';
import GithubIcon from 'grommet/components/icons/base/SocialGithub';
import Header from '../../components/Header/Header';
import { hz } from '../../lib/horizon';
import { AUTH_PROVIDERS } from '../../constants';
import './Login.scss';
const onLogin = () => {
hz.authEndpoint(AUTH_PROVIDERS.GITHUB)
.subscribe((endpoint) => {
window.location.replace(endpoint);
});
};
const Login = ({ user }) => (
<div className="app-wrapper">
<Header user={user} />
<main className="main-content">
<div className="login-container">
<Heading className="title" margin="large">hzPictionary</Heading>
<Button
icon={<GithubIcon />}
label="Login with Github"
fill
style={{ width: 'initial', alignSelf: 'center' }}
onClick={e => onLogin(e)}
/>
</div>
</main>
</div>
);
export default Login;
|
src/js/pages/Home.js | hadnazzar/ModernBusinessBootstrap-ReactComponent | import React from 'react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import Body from '../components/Body';
import Carousel from '../components/Carousel';
import ThreeBoxes from '../components/ThreeBoxes';
import PortfolioSixPic from '../components/PortfolioSixPic';
import FeaturesRightImg from '../components/FeaturesRightImg';
import ActionButton from '../components/ActionButton';
import {Link} from "react-router";
export default class Layout extends React.Component {
constructor() {
super();
this.state = {
title:"Welcome to Momoware!",
};
}
changeTitle(title){
this.setState({title});
}
navigate() {
console.log(this.props);
}
render() {
return(
<div>
<Header/>
<Carousel/>
<ThreeBoxes/>
<PortfolioSixPic/>
<FeaturesRightImg/>
<ActionButton/>
</div>
);
}
}
|
docs/src/pages/demos/selection-controls/RadioButtons.js | Kagami/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import green from '@material-ui/core/colors/green';
import Radio from '@material-ui/core/Radio';
import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked';
import RadioButtonCheckedIcon from '@material-ui/icons/RadioButtonChecked';
const styles = {
root: {
color: green[600],
'&$checked': {
color: green[500],
},
},
checked: {},
};
class RadioButtons extends React.Component {
state = {
selectedValue: 'a',
};
handleChange = event => {
this.setState({ selectedValue: event.target.value });
};
render() {
const { classes } = this.props;
return (
<div>
<Radio
checked={this.state.selectedValue === 'a'}
onChange={this.handleChange}
value="a"
name="radio-button-demo"
aria-label="A"
/>
<Radio
checked={this.state.selectedValue === 'b'}
onChange={this.handleChange}
value="b"
name="radio-button-demo"
aria-label="B"
/>
<Radio
checked={this.state.selectedValue === 'c'}
onChange={this.handleChange}
value="c"
name="radio-button-demo"
aria-label="C"
classes={{
root: classes.root,
checked: classes.checked,
}}
/>
<Radio
checked={this.state.selectedValue === 'd'}
onChange={this.handleChange}
value="d"
color="default"
name="radio-button-demo"
aria-label="D"
/>
<Radio
checked={this.state.selectedValue === 'e'}
onChange={this.handleChange}
value="e"
color="default"
name="radio-button-demo"
aria-label="E"
icon={<RadioButtonUncheckedIcon fontSize="small" />}
checkedIcon={<RadioButtonCheckedIcon fontSize="small" />}
/>
</div>
);
}
}
RadioButtons.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(RadioButtons);
|
node_modules/react-icons/md/panorama-wide-angle.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const MdPanoramaWideAngle = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m20 6.6q6 0 13.3 1.3l1.5 0.2 0.4 1.5q1.4 5.2 1.4 10.4t-1.4 10.4l-0.4 1.5-1.5 0.2q-7.3 1.3-13.3 1.3t-13.3-1.3l-1.5-0.2-0.4-1.5q-1.4-5.2-1.4-10.4t1.4-10.4l0.4-1.5 1.5-0.2q7.3-1.3 13.3-1.3z m0 3.4q-5.5 0-12.2 1.1-1.2 4.4-1.2 8.9t1.2 8.9q6.7 1.1 12.2 1.1t12.2-1.1q1.2-4.4 1.2-8.9t-1.2-8.9q-6.7-1.1-12.2-1.1z"/></g>
</Icon>
)
export default MdPanoramaWideAngle
|
src/components/App.js | niekert/soundify | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import styled, { ThemeProvider } from 'styled-components';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import { prop } from 'styled-tools';
import theme from 'theme';
// import ModalContainer from 'scenes/modals';
import PlayerContainer from 'scenes/player';
import UserProfileContainer from 'scenes/userProfile';
import TopBarContainer from 'containers/TopBarContainer';
import SidebarContainer from 'containers/SidebarContainer';
import LogoutContainer from 'containers/LogoutContainer';
import HomeContainer from 'containers/HomeContainer';
import LoginContainer from 'containers/LoginContainer';
import TrackContainer from 'scenes/track';
import TimelineContainer from 'scenes/timeline';
const AppShell = styled.div`
height: 100vh;
width: 100vw;
display: grid;
grid-template: 50px minMax(0, 1fr) 75px / 200px 1fr;
background: ${prop('theme.colors.primaryBackground')};
color: ${prop('theme.colors.primaryText')};
`;
const MainContent = styled.div`
grid-row: 2;
grid-column: 2;
flex: 1;
overflow-x: hidden;
overflow-y: auto;
display: flex;
background: ${prop('theme.colors.reverse.background')};
color: ${prop('theme.colors.reverse.primaryText')};
`;
const AuthedShell = () =>
<AppShell>
{window.location.pathname.includes('index.html') && <Redirect to="/" />}
<Route path="/" component={SidebarContainer} />
<TopBarContainer />
<MainContent>
<Route path="/logout" component={LogoutContainer} />
<Route exact path="/" component={HomeContainer} />
<Route path="index.html" component={HomeContainer} />
<Route
path="/(playlist|stream|likes|search)/:id?"
component={TimelineContainer}
/>
<Route path="/track/:trackId" component={TrackContainer} />
<Route
path="/profile/:profileId/:feedId?"
component={UserProfileContainer}
/>
{/* <ModalContainer /> */}
</MainContent>
<PlayerContainer />
</AppShell>;
class App extends Component {
static propTypes = {
user: PropTypes.object,
};
static defaultProps = {
user: null,
};
render() {
return (
<Router>
<ThemeProvider theme={theme}>
{this.props.user ? <AuthedShell /> : <LoginContainer />}
</ThemeProvider>
</Router>
);
}
}
export default DragDropContext(HTML5Backend)(App);
|
js/cards/SwitchCard/SwitchCard.js | Learnone/ShanghaiTechAPP | import React, { Component } from 'react';
import { View, ScrollView } from 'react-native';
import { connect } from 'react-redux';
import { Text, Button, Icon } from 'native-base';
import compose from 'lodash/fp/compose';
import curry from 'lodash/fp/curry';
import { FlipCard } from '../../cards';
import { SwitchIcon } from '../../components';
import { pushCard } from '../../actions/cardflow';
import styles from './styles';
const splitBy = curry((number, array) =>
array.reduce((previousReturn, current, index) => {
const newReturn = previousReturn;
if (Math.floor(index / number) === index / number) {
newReturn.push([]);
}
newReturn[Math.floor(index / number)].push(current);
return newReturn;
}, []));
const getIconArray = compose(splitBy(2), splitBy(4));
function bindAction(dispatch) {
return {
pushCard: (cardMeta) => dispatch(pushCard(cardMeta))
};
}
@connect(null, bindAction)
export default class SwitchCard extends Component {
static propTypes = {
cardMeta: React.PropTypes.object.isRequired,
pushCard: React.PropTypes.func.isRequired,
};
render() {
return (
<FlipCard noIcons cardMeta={this.props.cardMeta} >
<View style={styles.btnContainer}>
{
this.props.cardMeta.icons.map((icon, index) => (
<SwitchIcon key={index} iconInfo={icon} action={this.props.pushCard} parentPosition={this.props.cardMeta.position} />
))
}
</View>
</FlipCard>
);
}
}
|
src/svg-icons/maps/navigation.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsNavigation = (props) => (
<SvgIcon {...props}>
<path d="M12 2L4.5 20.29l.71.71L12 18l6.79 3 .71-.71z"/>
</SvgIcon>
);
MapsNavigation = pure(MapsNavigation);
MapsNavigation.displayName = 'MapsNavigation';
MapsNavigation.muiName = 'SvgIcon';
export default MapsNavigation;
|
src/components/comment_list.js | kors-mk5/react-starter | import React, { Component } from 'react';
import { connect } from 'react-redux';
const CommentList = (props) => {
const list = props.comments.map(comment => <li key={comment}>{comment}</li>);
return(
<ul className="comment-list">{list}</ul>
);
};
function mapStateToProps(state) {
return {comments: state.comments};
}
export default connect(mapStateToProps)(CommentList); |
files/react/15.0.0-rc.2/react-with-addons.js | gswalden/jsdelivr | /**
* React (with addons) v15.0.0-rc.2
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.React = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AutoFocusUtils
*/
'use strict';
var ReactDOMComponentTree = _dereq_(43);
var focusNode = _dereq_(166);
var AutoFocusUtils = {
focusDOMComponent: function () {
focusNode(ReactDOMComponentTree.getNodeFromInstance(this));
}
};
module.exports = AutoFocusUtils;
},{"166":166,"43":43}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013-present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BeforeInputEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(19);
var ExecutionEnvironment = _dereq_(158);
var FallbackCompositionState = _dereq_(20);
var SyntheticCompositionEvent = _dereq_(112);
var SyntheticInputEvent = _dereq_(116);
var keyOf = _dereq_(176);
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
var topLevelTypes = EventConstants.topLevelTypes;
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({ onBeforeInput: null }),
captured: keyOf({ onBeforeInputCapture: null })
},
dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste]
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionEnd: null }),
captured: keyOf({ onCompositionEndCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionStart: null }),
captured: keyOf({ onCompositionStartCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionUpdate: null }),
captured: keyOf({ onCompositionUpdateCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
}
};
// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
// Track the current IME composition fallback object, if any.
var currentComposition = null;
/**
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(nativeEventTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topCompositionEnd:
return getDataFromCustomEvent(nativeEvent);
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
if (currentComposition) {
if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
return chars;
}
return null;
}
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
return String.fromCharCode(nativeEvent.which);
}
return null;
case topLevelTypes.topCompositionEnd:
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)];
}
};
module.exports = BeforeInputEventPlugin;
},{"112":112,"116":116,"15":15,"158":158,"176":176,"19":19,"20":20}],3:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSProperty
*/
'use strict';
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridRow: true,
gridColumn: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: true,
backgroundColor: true,
backgroundImage: true,
backgroundPositionX: true,
backgroundPositionY: true,
backgroundRepeat: true
},
backgroundPosition: {
backgroundPositionX: true,
backgroundPositionY: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
},
outline: {
outlineWidth: true,
outlineStyle: true,
outlineColor: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],4:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSPropertyOperations
*/
'use strict';
var CSSProperty = _dereq_(3);
var ExecutionEnvironment = _dereq_(158);
var ReactPerf = _dereq_(88);
var camelizeStyleName = _dereq_(160);
var dangerousStyleValue = _dereq_(129);
var hyphenateStyleName = _dereq_(171);
var memoizeStringOnly = _dereq_(178);
var warning = _dereq_(182);
var processStyleName = memoizeStringOnly(function (styleName) {
return hyphenateStyleName(styleName);
});
var hasShorthandPropertyBug = false;
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
var tempStyle = document.createElement('div').style;
try {
// IE8 throws "Invalid argument." if resetting shorthand style properties.
tempStyle.font = '';
} catch (e) {
hasShorthandPropertyBug = true;
}
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if ("development" !== 'production') {
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnedForNaNValue = false;
var warnHyphenatedStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
"development" !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined;
};
var warnBadVendoredStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
"development" !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined;
};
var warnStyleValueWithSemicolon = function (name, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
"development" !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined;
};
var warnStyleValueIsNaN = function (name, value) {
if (warnedForNaNValue) {
return;
}
warnedForNaNValue = true;
"development" !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property', name) : undefined;
};
/**
* @param {string} name
* @param {*} value
*/
var warnValidStyle = function (name, value) {
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value);
}
if (typeof value === 'number' && isNaN(value)) {
warnStyleValueIsNaN(name, value);
}
};
}
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @param {ReactDOMComponent} component
* @return {?string}
*/
createMarkupForStyles: function (styles, component) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if ("development" !== 'production') {
warnValidStyle(styleName, styleValue);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue, component) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function (node, styles, component) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if ("development" !== 'production') {
warnValidStyle(styleName, styles[styleName]);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName], component);
if (styleName === 'float' || styleName === 'cssFloat') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', {
setValueForStyles: 'setValueForStyles'
});
module.exports = CSSPropertyOperations;
},{"129":129,"158":158,"160":160,"171":171,"178":178,"182":182,"3":3,"88":88}],5:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CallbackQueue
*/
'use strict';
var PooledClass = _dereq_(25);
var assign = _dereq_(24);
var invariant = _dereq_(172);
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null;
this._contexts = null;
}
assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function (callback, context) {
this._callbacks = this._callbacks || [];
this._contexts = this._contexts || [];
this._callbacks.push(callback);
this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function () {
var callbacks = this._callbacks;
var contexts = this._contexts;
if (callbacks) {
!(callbacks.length === contexts.length) ? "development" !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined;
this._callbacks = null;
this._contexts = null;
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
checkpoint: function () {
return this._callbacks ? this._callbacks.length : 0;
},
rollback: function (len) {
if (this._callbacks) {
this._callbacks.length = len;
this._contexts.length = len;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function () {
this._callbacks = null;
this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function () {
this.reset();
}
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
},{"172":172,"24":24,"25":25}],6:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ChangeEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(16);
var EventPropagators = _dereq_(19);
var ExecutionEnvironment = _dereq_(158);
var ReactDOMComponentTree = _dereq_(43);
var ReactUpdates = _dereq_(104);
var SyntheticEvent = _dereq_(114);
var getEventTarget = _dereq_(137);
var isEventSupported = _dereq_(144);
var isTextInputElement = _dereq_(145);
var keyOf = _dereq_(176);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({ onChange: null }),
captured: keyOf({ onChangeCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange]
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementInst = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue(false);
}
function startWatchingForChangeEventIE8(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementInst = null;
}
function getTargetInstForChangeEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topChange) {
return targetInst;
}
}
function handleEventsForChangeEventIE8(topLevelType, target, targetInst) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(target, targetInst);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events.
// IE10+ fire input events to often, such when a placeholder
// changes or when an input with a placeholder is focused.
isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 11);
}
/**
* (For IE <=11) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function () {
return activeElementValueProp.get.call(this);
},
set: function (val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For IE <=11) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
// on DOM elements
Object.defineProperty(activeElement, 'value', newValueProp);
if (activeElement.attachEvent) {
activeElement.attachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.addEventListener('propertychange', handlePropertyChange, false);
}
}
/**
* (For IE <=11) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
if (activeElement.detachEvent) {
activeElement.detachEvent('onpropertychange', handlePropertyChange);
} else {
activeElement.removeEventListener('propertychange', handlePropertyChange, false);
}
activeElement = null;
activeElementInst = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For IE <=11) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetInstForInputEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return targetInst;
}
}
function handleEventsForInputEventIE(topLevelType, target, targetInst) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9-11, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(target, targetInst);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetInstForInputEventIE(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementInst;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}
function getTargetInstForClickEvent(topLevelType, targetInst) {
if (topLevelType === topLevelTypes.topClick) {
return targetInst;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
var getTargetInstFunc, handleEventFunc;
if (shouldUseChangeEvent(targetNode)) {
if (doesChangeEventBubble) {
getTargetInstFunc = getTargetInstForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(targetNode)) {
if (isInputEventSupported) {
getTargetInstFunc = getTargetInstForInputEvent;
} else {
getTargetInstFunc = getTargetInstForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(targetNode)) {
getTargetInstFunc = getTargetInstForClickEvent;
}
if (getTargetInstFunc) {
var inst = getTargetInstFunc(topLevelType, targetInst);
if (inst) {
var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget);
event.type = 'change';
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(topLevelType, targetNode, targetInst);
}
}
};
module.exports = ChangeEventPlugin;
},{"104":104,"114":114,"137":137,"144":144,"145":145,"15":15,"158":158,"16":16,"176":176,"19":19,"43":43}],7:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMChildrenOperations
*/
'use strict';
var DOMLazyTree = _dereq_(8);
var Danger = _dereq_(12);
var ReactMultiChildUpdateTypes = _dereq_(83);
var ReactPerf = _dereq_(88);
var createMicrosoftUnsafeLocalFunction = _dereq_(128);
var setInnerHTML = _dereq_(149);
var setTextContent = _dereq_(150);
function getNodeAfter(parentNode, node) {
// Special case for text components, which return [open, close] comments
// from getNativeNode.
if (Array.isArray(node)) {
node = node[1];
}
return node ? node.nextSibling : parentNode.firstChild;
}
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) {
// We rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. (Using `undefined` is not allowed by all browsers so
// we are careful to use `null`.)
parentNode.insertBefore(childNode, referenceNode);
});
function insertLazyTreeChildAt(parentNode, childTree, referenceNode) {
DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode);
}
function moveChild(parentNode, childNode, referenceNode) {
if (Array.isArray(childNode)) {
moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode);
} else {
insertChildAt(parentNode, childNode, referenceNode);
}
}
function removeChild(parentNode, childNode) {
if (Array.isArray(childNode)) {
var closingComment = childNode[1];
childNode = childNode[0];
removeDelimitedText(parentNode, childNode, closingComment);
parentNode.removeChild(closingComment);
}
parentNode.removeChild(childNode);
}
function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) {
var node = openingComment;
while (true) {
var nextNode = node.nextSibling;
insertChildAt(parentNode, node, referenceNode);
if (node === closingComment) {
break;
}
node = nextNode;
}
}
function removeDelimitedText(parentNode, startNode, closingComment) {
while (true) {
var node = startNode.nextSibling;
if (node === closingComment) {
// The closing comment is removed by ReactMultiChild.
break;
} else {
parentNode.removeChild(node);
}
}
}
function replaceDelimitedText(openingComment, closingComment, stringText) {
var parentNode = openingComment.parentNode;
var nodeAfterComment = openingComment.nextSibling;
if (nodeAfterComment === closingComment) {
// There are no text nodes between the opening and closing comments; insert
// a new one if stringText isn't empty.
if (stringText) {
insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment);
}
} else {
if (stringText) {
// Set the text content of the first node after the opening comment, and
// remove all following nodes up until the closing comment.
setTextContent(nodeAfterComment, stringText);
removeDelimitedText(parentNode, nodeAfterComment, closingComment);
} else {
removeDelimitedText(parentNode, openingComment, closingComment);
}
}
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: setTextContent,
replaceDelimitedText: replaceDelimitedText,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
processUpdates: function (parentNode, updates) {
for (var k = 0; k < updates.length; k++) {
var update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode));
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode));
break;
case ReactMultiChildUpdateTypes.SET_MARKUP:
setInnerHTML(parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
removeChild(parentNode, update.fromNode);
break;
}
}
}
};
ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', {
updateTextContent: 'updateTextContent',
replaceDelimitedText: 'replaceDelimitedText'
});
module.exports = DOMChildrenOperations;
},{"12":12,"128":128,"149":149,"150":150,"8":8,"83":83,"88":88}],8:[function(_dereq_,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMLazyTree
*/
'use strict';
var createMicrosoftUnsafeLocalFunction = _dereq_(128);
var setTextContent = _dereq_(150);
/**
* In IE (8-11) and Edge, appending nodes with no children is dramatically
* faster than appending a full subtree, so we essentially queue up the
* .appendChild calls here and apply them so each node is added to its parent
* before any children are added.
*
* In other browsers, doing so is slower or neutral compared to the other order
* (in Firefox, twice as slow) so we only do this inversion in IE.
*
* See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode.
*/
var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent);
function insertTreeChildren(tree) {
if (!enableLazy) {
return;
}
var node = tree.node;
var children = tree.children;
if (children.length) {
for (var i = 0; i < children.length; i++) {
insertTreeBefore(node, children[i], null);
}
} else if (tree.html != null) {
node.innerHTML = tree.html;
} else if (tree.text != null) {
setTextContent(node, tree.text);
}
}
var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) {
// DocumentFragments aren't actually part of the DOM after insertion so
// appending children won't update the DOM. We need to ensure the fragment
// is properly populated first, breaking out of our lazy approach for just
// this level.
if (tree.node.nodeType === 11) {
insertTreeChildren(tree);
parentNode.insertBefore(tree.node, referenceNode);
} else {
parentNode.insertBefore(tree.node, referenceNode);
insertTreeChildren(tree);
}
});
function replaceChildWithTree(oldNode, newTree) {
oldNode.parentNode.replaceChild(newTree.node, oldNode);
insertTreeChildren(newTree);
}
function queueChild(parentTree, childTree) {
if (enableLazy) {
parentTree.children.push(childTree);
} else {
parentTree.node.appendChild(childTree.node);
}
}
function queueHTML(tree, html) {
if (enableLazy) {
tree.html = html;
} else {
tree.node.innerHTML = html;
}
}
function queueText(tree, text) {
if (enableLazy) {
tree.text = text;
} else {
setTextContent(tree.node, text);
}
}
function DOMLazyTree(node) {
return {
node: node,
children: [],
html: null,
text: null
};
}
DOMLazyTree.insertTreeBefore = insertTreeBefore;
DOMLazyTree.replaceChildWithTree = replaceChildWithTree;
DOMLazyTree.queueChild = queueChild;
DOMLazyTree.queueHTML = queueHTML;
DOMLazyTree.queueText = queueText;
module.exports = DOMLazyTree;
},{"128":128,"150":150}],9:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMNamespaces
*/
'use strict';
var DOMNamespaces = {
html: 'http://www.w3.org/1999/xhtml',
mathml: 'http://www.w3.org/1998/Math/MathML',
svg: 'http://www.w3.org/2000/svg'
};
module.exports = DOMNamespaces;
},{}],10:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMProperty
*/
'use strict';
var invariant = _dereq_(172);
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_PROPERTY: 0x1,
HAS_SIDE_EFFECTS: 0x2,
HAS_BOOLEAN_VALUE: 0x4,
HAS_NUMERIC_VALUE: 0x8,
HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x20,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
* attribute namespace URL. (Attribute names not specified use no namespace.)
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function (domPropertyConfig) {
var Injection = DOMPropertyInjection;
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
}
for (var propName in Properties) {
!!DOMProperty.properties.hasOwnProperty(propName) ? "development" !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined;
var lowerCased = propName.toLowerCase();
var propConfig = Properties[propName];
var propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS),
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
};
!(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined;
!(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined;
if ("development" !== 'production') {
DOMProperty.getPossibleStandardName[lowerCased] = propName;
}
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
propertyInfo.attributeName = attributeName;
if ("development" !== 'production') {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
}
if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
}
if (DOMPropertyNames.hasOwnProperty(propName)) {
propertyInfo.propertyName = DOMPropertyNames[propName];
}
if (DOMMutationMethods.hasOwnProperty(propName)) {
propertyInfo.mutationMethod = DOMMutationMethods[propName];
}
DOMProperty.properties[propName] = propertyInfo;
}
}
};
/* eslint-disable max-len */
var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
/* eslint-enable max-len */
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
ROOT_ATTRIBUTE_NAME: 'data-reactroot',
ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR,
ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040',
/**
* Map from property "standard name" to an object with info about how to set
* the property in the DOM. Each object contains:
*
* attributeName:
* Used when rendering markup or with `*Attribute()`.
* attributeNamespace
* propertyName:
* Used on DOM node instances. (This includes properties that mutate due to
* external factors.)
* mutationMethod:
* If non-null, used instead of the property or `setAttribute()` after
* initial render.
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* hasSideEffects:
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. If true, we read from
* the DOM before updating to ensure that the value is only set if it has
* changed.
* hasBooleanValue:
* Whether the property should be removed when set to a falsey value.
* hasNumericValue:
* Whether the property must be numeric or parse as a numeric and should be
* removed when set to a falsey value.
* hasPositiveNumericValue:
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* hasOverloadedBooleanValue:
* Whether the property can be used as a flag as well as with a value.
* Removed when strictly equal to false; present without a value when
* strictly equal to true; present with a value otherwise.
*/
properties: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties. Available only in __DEV__.
* @type {Object}
*/
getPossibleStandardName: "development" !== 'production' ? {} : null,
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function (attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
},{"172":172}],11:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DOMPropertyOperations
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactDOMInstrumentation = _dereq_(51);
var ReactPerf = _dereq_(88);
var quoteAttributeValueForBrowser = _dereq_(147);
var warning = _dereq_(182);
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (validatedAttributeNameCache.hasOwnProperty(attributeName)) {
return true;
}
if (illegalAttributeNameCache.hasOwnProperty(attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
"development" !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function (id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function (node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
createMarkupForRoot: function () {
return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""';
},
setAttributeForRoot: function (node) {
node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, '');
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function (name, value) {
if ("development" !== 'production') {
ReactDOMInstrumentation.debugTool.onCreateMarkupForProperty(name, value);
}
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.attributeName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
}
return null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function (name, value) {
if (!isAttributeNameSafe(name) || value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function (node, name, value) {
if ("development" !== 'production') {
ReactDOMInstrumentation.debugTool.onSetValueForProperty(node, name, value);
}
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(propertyInfo, value)) {
this.deleteValueForProperty(node, name);
} else if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
// property type before comparing; only `value` does and is string.
if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propName] = value;
}
} else {
var attributeName = propertyInfo.attributeName;
var namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (namespace) {
node.setAttributeNS(namespace, attributeName, '' + value);
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
node.setAttribute(attributeName, '');
} else {
node.setAttribute(attributeName, '' + value);
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function (node, name) {
if ("development" !== 'production') {
ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name);
}
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
if (propertyInfo.hasBooleanValue) {
// No HAS_SIDE_EFFECTS logic here, only `value` has it and is string.
node[propName] = false;
} else {
if (!propertyInfo.hasSideEffects || '' + node[propName] !== '') {
node[propName] = '';
}
}
} else {
node.removeAttribute(propertyInfo.attributeName);
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
}
}
};
ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', {
setValueForProperty: 'setValueForProperty',
setValueForAttribute: 'setValueForAttribute',
deleteValueForProperty: 'deleteValueForProperty'
});
module.exports = DOMPropertyOperations;
},{"10":10,"147":147,"182":182,"51":51,"88":88}],12:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Danger
*/
'use strict';
var DOMLazyTree = _dereq_(8);
var ExecutionEnvironment = _dereq_(158);
var createNodesFromMarkup = _dereq_(163);
var emptyFunction = _dereq_(164);
var getMarkupWrap = _dereq_(168);
var invariant = _dereq_(172);
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
var Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function (markupList) {
!ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined;
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
!markupList[i] ? "development" !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined;
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
var resultIndex;
for (resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ');
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags.
);
for (var j = 0; j < renderNodes.length; ++j) {
var renderNode = renderNodes[j];
if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
!!resultList.hasOwnProperty(resultIndex) ? "development" !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined;
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if ("development" !== 'production') {
console.error('Danger: Discarding unexpected node:', renderNode);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
!(resultListAssignmentCount === resultList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined;
!(resultList.length === markupList.length) ? "development" !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined;
return resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) {
!ExecutionEnvironment.canUseDOM ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
!markup ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined;
!(oldChild.nodeName !== 'HTML') ? "development" !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined;
if (typeof markup === 'string') {
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
} else {
DOMLazyTree.replaceChildWithTree(oldChild, markup);
}
}
};
module.exports = Danger;
},{"158":158,"163":163,"164":164,"168":168,"172":172,"8":8}],13:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule DefaultEventPluginOrder
*/
'use strict';
var keyOf = _dereq_(176);
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })];
module.exports = DefaultEventPluginOrder;
},{"176":176}],14:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EnterLeaveEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(19);
var ReactDOMComponentTree = _dereq_(43);
var SyntheticMouseEvent = _dereq_(118);
var keyOf = _dereq_(176);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({ onMouseEnter: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
},
mouseLeave: {
registrationName: keyOf({ onMouseLeave: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
}
};
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*/
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (nativeEventTarget.window === nativeEventTarget) {
// `nativeEventTarget` is probably a window object.
win = nativeEventTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = targetInst;
var related = nativeEvent.relatedTarget || nativeEvent.toElement;
to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null;
} else {
// Moving to a node from outside the window.
from = null;
to = targetInst;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from);
var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to);
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = toNode;
enter.relatedTarget = fromNode;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to);
return [leave, enter];
}
};
module.exports = EnterLeaveEventPlugin;
},{"118":118,"15":15,"176":176,"19":19,"43":43}],15:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventConstants
*/
'use strict';
var keyMirror = _dereq_(175);
var PropagationPhases = keyMirror({ bubbled: null, captured: null });
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topAbort: null,
topAnimationEnd: null,
topAnimationIteration: null,
topAnimationStart: null,
topBlur: null,
topCanPlay: null,
topCanPlayThrough: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topDurationChange: null,
topEmptied: null,
topEncrypted: null,
topEnded: null,
topError: null,
topFocus: null,
topInput: null,
topInvalid: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topLoadedData: null,
topLoadedMetadata: null,
topLoadStart: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topPause: null,
topPlay: null,
topPlaying: null,
topProgress: null,
topRateChange: null,
topReset: null,
topScroll: null,
topSeeked: null,
topSeeking: null,
topSelectionChange: null,
topStalled: null,
topSubmit: null,
topSuspend: null,
topTextInput: null,
topTimeUpdate: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topTransitionEnd: null,
topVolumeChange: null,
topWaiting: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
},{"175":175}],16:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginHub
*/
'use strict';
var EventPluginRegistry = _dereq_(17);
var EventPluginUtils = _dereq_(18);
var ReactErrorUtils = _dereq_(68);
var accumulateInto = _dereq_(125);
var forEachAccumulated = _dereq_(133);
var invariant = _dereq_(172);
/**
* Internal store for event listeners
*/
var listenerBank = {};
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @private
*/
var executeDispatchesAndRelease = function (event, simulated) {
if (event) {
EventPluginUtils.executeDispatchesInOrder(event, simulated);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
var executeDispatchesAndReleaseSimulated = function (e) {
return executeDispatchesAndRelease(e, true);
};
var executeDispatchesAndReleaseTopLevel = function (e) {
return executeDispatchesAndRelease(e, false);
};
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {function} listener The callback to store.
*/
putListener: function (inst, registrationName, listener) {
!(typeof listener === 'function') ? "development" !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined;
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[inst._rootNodeID] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.didPutListener) {
PluginModule.didPutListener(inst, registrationName, listener);
}
},
/**
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function (inst, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[inst._rootNodeID];
},
/**
* Deletes a listener from the registration bank.
*
* @param {object} inst The instance, which is the source of events.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function (inst, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
delete bankForRegistrationName[inst._rootNodeID];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {object} inst The instance, which is the source of events.
*/
deleteAllListeners: function (inst) {
for (var registrationName in listenerBank) {
if (!listenerBank[registrationName][inst._rootNodeID]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(inst, registrationName);
}
delete listenerBank[registrationName][inst._rootNodeID];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0; i < plugins.length; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
if (extractedEvents) {
events = accumulateInto(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function (events) {
if (events) {
eventQueue = accumulateInto(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function (simulated) {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
if (simulated) {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
} else {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
}
!!eventQueue ? "development" !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined;
// This would be a good time to rethrow if any of the event handlers threw.
ReactErrorUtils.rethrowCaughtError();
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function () {
listenerBank = {};
},
__getListenerBank: function () {
return listenerBank;
}
};
module.exports = EventPluginHub;
},{"125":125,"133":133,"17":17,"172":172,"18":18,"68":68}],17:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginRegistry
*/
'use strict';
var invariant = _dereq_(172);
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
!(pluginIndex > -1) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined;
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
!PluginModule.extractEvents ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined;
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
!publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined;
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
!!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined;
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, PluginModule, eventName);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule, eventName) {
!!EventPluginRegistry.registrationNameModules[registrationName] ? "development" !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined;
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies;
if ("development" !== 'production') {
var lowerCasedName = registrationName.toLowerCase();
EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName;
}
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Mapping from lowercase registration names to the properly cased version,
* used to warn in the case of missing event handlers. Available
* only in __DEV__.
* @type {Object}
*/
possibleRegistrationNames: "development" !== 'production' ? {} : null,
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function (InjectedEventPluginOrder) {
!!EventPluginOrder ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined;
// Clone the ordering so it cannot be dynamically mutated.
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function (injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var PluginModule = injectedNamesToPlugins[pluginName];
if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) {
!!namesToPlugins[pluginName] ? "development" !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined;
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function (event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function () {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
if ("development" !== 'production') {
var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames;
for (var lowerCasedName in possibleRegistrationNames) {
if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) {
delete possibleRegistrationNames[lowerCasedName];
}
}
}
}
};
module.exports = EventPluginRegistry;
},{"172":172}],18:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPluginUtils
*/
'use strict';
var EventConstants = _dereq_(15);
var ReactErrorUtils = _dereq_(68);
var invariant = _dereq_(172);
var warning = _dereq_(182);
/**
* Injected dependencies:
*/
/**
* - `ComponentTree`: [required] Module that can convert between React instances
* and actual node references.
*/
var ComponentTree;
var TreeTraversal;
var injection = {
injectComponentTree: function (Injected) {
ComponentTree = Injected;
if ("development" !== 'production') {
"development" !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : undefined;
}
},
injectTreeTraversal: function (Injected) {
TreeTraversal = Injected;
if ("development" !== 'production') {
"development" !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : undefined;
}
}
};
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if ("development" !== 'production') {
validateEventDispatches = function (event) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
var listenersIsArr = Array.isArray(dispatchListeners);
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
var instancesIsArr = Array.isArray(dispatchInstances);
var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
"development" !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined;
};
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @param {function} listener Application-level callback
* @param {*} inst Internal component instance
*/
function executeDispatch(event, simulated, listener, inst) {
var type = event.type || 'unknown-event';
event.currentTarget = EventPluginUtils.getNodeFromInstance(inst);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event);
}
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
if ("development" !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, simulated, dispatchListeners, dispatchInstances);
}
event._dispatchListeners = null;
event._dispatchInstances = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchInstances = event._dispatchInstances;
if ("development" !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and Instances are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchInstances[i])) {
return dispatchInstances[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchInstances)) {
return dispatchInstances;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchInstances = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if ("development" !== 'production') {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchInstance = event._dispatchInstances;
!!Array.isArray(dispatchListener) ? "development" !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined;
event.currentTarget = EventPluginUtils.getNodeFromInstance(dispatchInstance);
var res = dispatchListener ? dispatchListener(event) : null;
event.curentTarget = null;
event._dispatchListeners = null;
event._dispatchInstances = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getInstanceFromNode: function (node) {
return ComponentTree.getInstanceFromNode(node);
},
getNodeFromInstance: function (node) {
return ComponentTree.getNodeFromInstance(node);
},
isAncestor: function (a, b) {
return TreeTraversal.isAncestor(a, b);
},
getLowestCommonAncestor: function (a, b) {
return TreeTraversal.getLowestCommonAncestor(a, b);
},
getParentInstance: function (inst) {
return TreeTraversal.getParentInstance(inst);
},
traverseTwoPhase: function (target, fn, arg) {
return TreeTraversal.traverseTwoPhase(target, fn, arg);
},
traverseEnterLeave: function (from, to, fn, argFrom, argTo) {
return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo);
},
injection: injection
};
module.exports = EventPluginUtils;
},{"15":15,"172":172,"182":182,"68":68}],19:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule EventPropagators
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(16);
var EventPluginUtils = _dereq_(18);
var accumulateInto = _dereq_(125);
var forEachAccumulated = _dereq_(133);
var warning = _dereq_(182);
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(inst, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(inst, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(inst, upwards, event) {
if ("development" !== 'production') {
"development" !== 'production' ? warning(inst, 'Dispatching inst must not be null') : undefined;
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(inst, event, phase);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We cannot perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
var targetInst = event._targetInst;
var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null;
EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(inst, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(inst, registrationName);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event._targetInst, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, from, to) {
EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
},{"125":125,"133":133,"15":15,"16":16,"18":18,"182":182}],20:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule FallbackCompositionState
*/
'use strict';
var PooledClass = _dereq_(25);
var assign = _dereq_(24);
var getTextContentAccessor = _dereq_(141);
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root;
this._startText = this.getText();
this._fallbackText = null;
}
assign(FallbackCompositionState.prototype, {
destructor: function () {
this._root = null;
this._startText = null;
this._fallbackText = null;
},
/**
* Get current text of input.
*
* @return {string}
*/
getText: function () {
if ('value' in this._root) {
return this._root.value;
}
return this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function () {
if (this._fallbackText) {
return this._fallbackText;
}
var start;
var startValue = this._startText;
var startLength = startValue.length;
var end;
var endValue = this.getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
this._fallbackText = endValue.slice(start, sliceTail);
return this._fallbackText;
}
});
PooledClass.addPoolingTo(FallbackCompositionState);
module.exports = FallbackCompositionState;
},{"141":141,"24":24,"25":25}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule HTMLDOMPropertyConfig
*/
'use strict';
var DOMProperty = _dereq_(10);
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')),
Properties: {
/**
* Standard Properties
*/
accept: 0,
acceptCharset: 0,
accessKey: 0,
action: 0,
allowFullScreen: HAS_BOOLEAN_VALUE,
allowTransparency: 0,
alt: 0,
async: HAS_BOOLEAN_VALUE,
autoComplete: 0,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: HAS_BOOLEAN_VALUE,
cellPadding: 0,
cellSpacing: 0,
charSet: 0,
challenge: 0,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
cite: 0,
classID: 0,
className: 0,
cols: HAS_POSITIVE_NUMERIC_VALUE,
colSpan: 0,
content: 0,
contentEditable: 0,
contextMenu: 0,
controls: HAS_BOOLEAN_VALUE,
coords: 0,
crossOrigin: 0,
data: 0, // For `<object />` acts as `src`.
dateTime: 0,
'default': HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: 0,
disabled: HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: 0,
encType: 0,
form: 0,
formAction: 0,
formEncType: 0,
formMethod: 0,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: 0,
frameBorder: 0,
headers: 0,
height: 0,
hidden: HAS_BOOLEAN_VALUE,
high: 0,
href: 0,
hrefLang: 0,
htmlFor: 0,
httpEquiv: 0,
icon: 0,
id: 0,
inputMode: 0,
integrity: 0,
is: 0,
keyParams: 0,
keyType: 0,
kind: 0,
label: 0,
lang: 0,
list: 0,
loop: HAS_BOOLEAN_VALUE,
low: 0,
manifest: 0,
marginHeight: 0,
marginWidth: 0,
max: 0,
maxLength: 0,
media: 0,
mediaGroup: 0,
method: 0,
min: 0,
minLength: 0,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: 0,
nonce: 0,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: 0,
pattern: 0,
placeholder: 0,
poster: 0,
preload: 0,
profile: 0,
radioGroup: 0,
readOnly: HAS_BOOLEAN_VALUE,
rel: 0,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: 0,
rows: HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: HAS_NUMERIC_VALUE,
sandbox: 0,
scope: 0,
scoped: HAS_BOOLEAN_VALUE,
scrolling: 0,
seamless: HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: 0,
size: HAS_POSITIVE_NUMERIC_VALUE,
sizes: 0,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: 0,
src: 0,
srcDoc: 0,
srcLang: 0,
srcSet: 0,
start: HAS_NUMERIC_VALUE,
step: 0,
style: 0,
summary: 0,
tabIndex: 0,
target: 0,
title: 0,
// Setting .type throws on non-<input> tags
type: 0,
useMap: 0,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: 0,
wmode: 0,
wrap: 0,
/**
* RDFa Properties
*/
about: 0,
datatype: 0,
inlist: 0,
prefix: 0,
// property is also supported for OpenGraph in meta tags.
property: 0,
resource: 0,
'typeof': 0,
vocab: 0,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: 0,
autoCorrect: 0,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: 0,
// color is for Safari mask-icon link
color: 0,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: 0,
itemScope: HAS_BOOLEAN_VALUE,
itemType: 0,
// itemID and itemRef are for Microdata support as well but
// only specified in the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: 0,
itemRef: 0,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: 0,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: 0,
// IE-only attribute that controls focus behavior
unselectable: 0
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {}
};
module.exports = HTMLDOMPropertyConfig;
},{"10":10}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule LinkedStateMixin
*/
'use strict';
var ReactLink = _dereq_(79);
var ReactStateSetters = _dereq_(98);
/**
* A simple mixin around ReactLink.forState().
*/
var LinkedStateMixin = {
/**
* Create a ReactLink that's linked to part of this component's state. The
* ReactLink will have the current value of this.state[key] and will call
* setState() when a change is requested.
*
* @param {string} key state key to update. Note: you may want to use keyOf()
* if you're using Google Closure Compiler advanced mode.
* @return {ReactLink} ReactLink instance linking to the state.
*/
linkState: function (key) {
return new ReactLink(this.state[key], ReactStateSetters.createStateKeySetter(this, key));
}
};
module.exports = LinkedStateMixin;
},{"79":79,"98":98}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule LinkedValueUtils
*/
'use strict';
var ReactPropTypes = _dereq_(91);
var ReactPropTypeLocations = _dereq_(90);
var invariant = _dereq_(172);
var warning = _dereq_(182);
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(inputProps) {
!(inputProps.checkedLink == null || inputProps.valueLink == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined;
}
function _assertValueLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.value == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined;
}
function _assertCheckedLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.checked == null && inputProps.onChange == null) ? "development" !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined;
}
var propTypes = {
value: function (props, propName, componentName) {
if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
checked: function (props, propName, componentName) {
if (!props[propName] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
onChange: ReactPropTypes.func
};
var loggedTypeFailures = {};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
checkPropTypes: function (tagName, props, owner) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum(owner);
"development" !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined;
}
}
},
/**
* @param {object} inputProps Props for form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function (inputProps) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.value;
}
return inputProps.value;
},
/**
* @param {object} inputProps Props for form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function (inputProps) {
if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.value;
}
return inputProps.checked;
},
/**
* @param {object} inputProps Props for form component
* @param {SyntheticEvent} event change event to handle
*/
executeOnChange: function (inputProps, event) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.requestChange(event.target.value);
} else if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.requestChange(event.target.checked);
} else if (inputProps.onChange) {
return inputProps.onChange.call(undefined, event);
}
}
};
module.exports = LinkedValueUtils;
},{"172":172,"182":182,"90":90,"91":91}],24:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
}
module.exports = assign;
},{}],25:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PooledClass
*/
'use strict';
var invariant = _dereq_(172);
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function (a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function (a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fourArgumentPooler = function (a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
var fiveArgumentPooler = function (a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function (instance) {
var Klass = this;
!(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{"172":172}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule React
*/
'use strict';
var ReactDOM = _dereq_(39);
var ReactDOMServer = _dereq_(55);
var ReactIsomorphic = _dereq_(78);
var assign = _dereq_(24);
// `version` will be added here by ReactIsomorphic.
var React = {};
assign(React, ReactIsomorphic);
React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM;
React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer;
module.exports = React;
},{"24":24,"39":39,"55":55,"78":78}],27:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactBrowserEventEmitter
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginRegistry = _dereq_(17);
var ReactEventEmitterMixin = _dereq_(69);
var ViewportMetrics = _dereq_(124);
var assign = _dereq_(24);
var getVendorPrefixedEventName = _dereq_(142);
var isEventSupported = _dereq_(144);
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var hasEventPageXY;
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topAbort: 'abort',
topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend',
topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration',
topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart',
topBlur: 'blur',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topScroll: 'scroll',
topSeeked: 'seeked',
topSeeking: 'seeking',
topSelectionChange: 'selectionchange',
topStalled: 'stalled',
topSuspend: 'suspend',
topTextInput: 'textInput',
topTimeUpdate: 'timeupdate',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend',
topVolumeChange: 'volumechange',
topWaiting: 'waiting',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* EventPluginHub.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function (ReactEventListener) {
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function (enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function () {
return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled());
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function (registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
if (dependency === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt);
}
} else if (dependency === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE);
}
} else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
}
// to make sure blur and focus event listeners are only attached once
isListening[topLevelTypes.topBlur] = true;
isListening[topLevelTypes.topFocus] = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
},
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when
* pageX/pageY isn't supported (legacy browsers).
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function () {
if (hasEventPageXY === undefined) {
hasEventPageXY = document.createEvent && 'pageX' in document.createEvent('MouseEvent');
}
if (!hasEventPageXY && !isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
}
});
module.exports = ReactBrowserEventEmitter;
},{"124":124,"142":142,"144":144,"15":15,"17":17,"24":24,"69":69}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCSSTransitionGroup
*/
'use strict';
var React = _dereq_(26);
var assign = _dereq_(24);
var ReactTransitionGroup = _dereq_(102);
var ReactCSSTransitionGroupChild = _dereq_(29);
function createTransitionTimeoutPropValidator(transitionType) {
var timeoutPropName = 'transition' + transitionType + 'Timeout';
var enabledPropName = 'transition' + transitionType;
return function (props) {
// If the transition is enabled
if (props[enabledPropName]) {
// If no timeout duration is provided
if (props[timeoutPropName] == null) {
return new Error(timeoutPropName + ' wasn\'t supplied to ReactCSSTransitionGroup: ' + 'this can cause unreliable animations and won\'t be supported in ' + 'a future version of React. See ' + 'https://fb.me/react-animation-transition-group-timeout for more ' + 'information.');
// If the duration isn't a number
} else if (typeof props[timeoutPropName] !== 'number') {
return new Error(timeoutPropName + ' must be a number (in milliseconds)');
}
}
};
}
var ReactCSSTransitionGroup = React.createClass({
displayName: 'ReactCSSTransitionGroup',
propTypes: {
transitionName: ReactCSSTransitionGroupChild.propTypes.name,
transitionAppear: React.PropTypes.bool,
transitionEnter: React.PropTypes.bool,
transitionLeave: React.PropTypes.bool,
transitionAppearTimeout: createTransitionTimeoutPropValidator('Appear'),
transitionEnterTimeout: createTransitionTimeoutPropValidator('Enter'),
transitionLeaveTimeout: createTransitionTimeoutPropValidator('Leave')
},
getDefaultProps: function () {
return {
transitionAppear: false,
transitionEnter: true,
transitionLeave: true
};
},
_wrapChild: function (child) {
// We need to provide this childFactory so that
// ReactCSSTransitionGroupChild can receive updates to name, enter, and
// leave while it is leaving.
return React.createElement(ReactCSSTransitionGroupChild, {
name: this.props.transitionName,
appear: this.props.transitionAppear,
enter: this.props.transitionEnter,
leave: this.props.transitionLeave,
appearTimeout: this.props.transitionAppearTimeout,
enterTimeout: this.props.transitionEnterTimeout,
leaveTimeout: this.props.transitionLeaveTimeout
}, child);
},
render: function () {
return React.createElement(ReactTransitionGroup, assign({}, this.props, { childFactory: this._wrapChild }));
}
});
module.exports = ReactCSSTransitionGroup;
},{"102":102,"24":24,"26":26,"29":29}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCSSTransitionGroupChild
*/
'use strict';
var React = _dereq_(26);
var ReactDOM = _dereq_(39);
var CSSCore = _dereq_(156);
var ReactTransitionEvents = _dereq_(101);
var onlyChild = _dereq_(146);
var TICK = 17;
var ReactCSSTransitionGroupChild = React.createClass({
displayName: 'ReactCSSTransitionGroupChild',
propTypes: {
name: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.shape({
enter: React.PropTypes.string,
leave: React.PropTypes.string,
active: React.PropTypes.string
}), React.PropTypes.shape({
enter: React.PropTypes.string,
enterActive: React.PropTypes.string,
leave: React.PropTypes.string,
leaveActive: React.PropTypes.string,
appear: React.PropTypes.string,
appearActive: React.PropTypes.string
})]).isRequired,
// Once we require timeouts to be specified, we can remove the
// boolean flags (appear etc.) and just accept a number
// or a bool for the timeout flags (appearTimeout etc.)
appear: React.PropTypes.bool,
enter: React.PropTypes.bool,
leave: React.PropTypes.bool,
appearTimeout: React.PropTypes.number,
enterTimeout: React.PropTypes.number,
leaveTimeout: React.PropTypes.number
},
transition: function (animationType, finishCallback, userSpecifiedDelay) {
var node = ReactDOM.findDOMNode(this);
if (!node) {
if (finishCallback) {
finishCallback();
}
return;
}
var className = this.props.name[animationType] || this.props.name + '-' + animationType;
var activeClassName = this.props.name[animationType + 'Active'] || className + '-active';
var timeout = null;
var endListener = function (e) {
if (e && e.target !== node) {
return;
}
clearTimeout(timeout);
CSSCore.removeClass(node, className);
CSSCore.removeClass(node, activeClassName);
ReactTransitionEvents.removeEndEventListener(node, endListener);
// Usually this optional callback is used for informing an owner of
// a leave animation and telling it to remove the child.
if (finishCallback) {
finishCallback();
}
};
CSSCore.addClass(node, className);
// Need to do this to actually trigger a transition.
this.queueClass(activeClassName);
// If the user specified a timeout delay.
if (userSpecifiedDelay) {
// Clean-up the animation after the specified delay
timeout = setTimeout(endListener, userSpecifiedDelay);
this.transitionTimeouts.push(timeout);
} else {
// DEPRECATED: this listener will be removed in a future version of react
ReactTransitionEvents.addEndEventListener(node, endListener);
}
},
queueClass: function (className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this.flushClassNameQueue, TICK);
}
},
flushClassNameQueue: function () {
if (this.isMounted()) {
this.classNameQueue.forEach(CSSCore.addClass.bind(CSSCore, ReactDOM.findDOMNode(this)));
}
this.classNameQueue.length = 0;
this.timeout = null;
},
componentWillMount: function () {
this.classNameQueue = [];
this.transitionTimeouts = [];
},
componentWillUnmount: function () {
if (this.timeout) {
clearTimeout(this.timeout);
}
this.transitionTimeouts.forEach(function (timeout) {
clearTimeout(timeout);
});
},
componentWillAppear: function (done) {
if (this.props.appear) {
this.transition('appear', done, this.props.appearTimeout);
} else {
done();
}
},
componentWillEnter: function (done) {
if (this.props.enter) {
this.transition('enter', done, this.props.enterTimeout);
} else {
done();
}
},
componentWillLeave: function (done) {
if (this.props.leave) {
this.transition('leave', done, this.props.leaveTimeout);
} else {
done();
}
},
render: function () {
return onlyChild(this.props.children);
}
});
module.exports = ReactCSSTransitionGroupChild;
},{"101":101,"146":146,"156":156,"26":26,"39":39}],30:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildReconciler
*/
'use strict';
var ReactReconciler = _dereq_(93);
var instantiateReactComponent = _dereq_(143);
var shouldUpdateReactComponent = _dereq_(152);
var traverseAllChildren = _dereq_(153);
var warning = _dereq_(182);
function instantiateChild(childInstances, child, name) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child);
}
}
/**
* ReactChildReconciler provides helpers for initializing or updating a set of
* children. Its output is suitable for passing it onto ReactMultiChild which
* does diffed reordering and insertion.
*/
var ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function (nestedChildNodes, transaction, context) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
return childInstances;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextChildren Flat child element maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function (prevChildren, nextChildren, removedNodes, transaction, context) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
if (!nextChildren && !prevChildren) {
return;
}
var name;
var prevChild;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) {
ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context);
nextChildren[name] = prevChild;
} else {
if (prevChild) {
removedNodes[name] = ReactReconciler.getNativeNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement);
nextChildren[name] = nextChildInstance;
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
prevChild = prevChildren[name];
removedNodes[name] = ReactReconciler.getNativeNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function (renderedChildren, safely) {
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild, safely);
}
}
}
};
module.exports = ReactChildReconciler;
},{"143":143,"152":152,"153":153,"182":182,"93":93}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactChildren
*/
'use strict';
var PooledClass = _dereq_(25);
var ReactElement = _dereq_(65);
var emptyFunction = _dereq_(164);
var traverseAllChildren = _dereq_(153);
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var fourArgumentPooler = PooledClass.fourArgumentPooler;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
ForEachBookKeeping.prototype.destructor = function () {
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func;
var context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
MapBookKeeping.prototype.destructor = function () {
this.result = null;
this.keyPrefix = null;
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result;
var keyPrefix = bookKeeping.keyPrefix;
var func = bookKeeping.func;
var context = bookKeeping.context;
var mappedChild = func.call(context, child, bookKeeping.count++);
if (Array.isArray(mappedChild)) {
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
} else if (mappedChild != null) {
if (ReactElement.isValidElement(mappedChild)) {
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
}
result.push(mappedChild);
}
}
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
var escapedPrefix = '';
if (prefix != null) {
escapedPrefix = escapeUserProvidedKey(prefix) + '/';
}
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
}
/**
* Maps children that are typically specified as `props.children`.
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
function forEachSingleChildDummy(traverseContext, child, name) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*/
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
count: countChildren,
toArray: toArray
};
module.exports = ReactChildren;
},{"153":153,"164":164,"25":25,"65":65}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactClass
*/
'use strict';
var ReactComponent = _dereq_(33);
var ReactElement = _dereq_(65);
var ReactPropTypeLocations = _dereq_(90);
var ReactPropTypeLocationNames = _dereq_(89);
var ReactNoopUpdateQueue = _dereq_(86);
var assign = _dereq_(24);
var emptyObject = _dereq_(165);
var invariant = _dereq_(172);
var keyMirror = _dereq_(175);
var keyOf = _dereq_(176);
var warning = _dereq_(182);
var MIXINS_KEY = keyOf({ mixins: null });
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function (Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function (Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function (Constructor, childContextTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext);
}
Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function (Constructor, contextTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context);
}
Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function (Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function (Constructor, propTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop);
}
Constructor.propTypes = assign({}, Constructor.propTypes, propTypes);
},
statics: function (Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function () {} };
// noop
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an invariant so components
// don't show up in prod but only in __DEV__
"development" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined;
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.OVERRIDE_BASE) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined;
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined;
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
!(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.') : invariant(false) : undefined;
!!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("development" !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
!!isReserved ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined;
var isInherited = name in Constructor;
!!isInherited ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined;
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
!(one && two && typeof one === 'object' && typeof two === 'object') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined;
for (var key in two) {
if (two.hasOwnProperty(key)) {
!(one[key] === undefined) ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined;
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if ("development" !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function (newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
"development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined;
} else if (!args.length) {
"development" !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function (newState, callback) {
this.updater.enqueueReplaceState(this, newState);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function () {
return this.updater.isMounted(this);
}
};
var ReactClassComponent = function () {};
assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function (spec) {
var Constructor = function (props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("development" !== 'production') {
"development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("development" !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (initialState === undefined && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined;
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if ("development" !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
!Constructor.prototype.render ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined;
"development" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined;
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
},
injection: {
injectMixin: function (mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactClass;
},{"165":165,"172":172,"175":175,"176":176,"182":182,"24":24,"33":33,"65":65,"86":86,"89":89,"90":90}],33:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponent
*/
'use strict';
var ReactNoopUpdateQueue = _dereq_(86);
var ReactInstrumentation = _dereq_(76);
var canDefineProperty = _dereq_(127);
var emptyObject = _dereq_(165);
var invariant = _dereq_(172);
var warning = _dereq_(182);
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
ReactComponent.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined;
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onSetState();
"development" !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined;
}
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if ("development" !== 'production') {
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
"development" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined;
return undefined;
}
});
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
module.exports = ReactComponent;
},{"127":127,"165":165,"172":172,"182":182,"76":76,"86":86}],34:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentBrowserEnvironment
*/
'use strict';
var DOMChildrenOperations = _dereq_(7);
var ReactDOMIDOperations = _dereq_(49);
var ReactPerf = _dereq_(88);
/**
* Abstracts away all functionality of the reconciler that requires knowledge of
* the browser context. TODO: These callers should be refactored to avoid the
* need for this injection.
*/
var ReactComponentBrowserEnvironment = {
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function (rootNodeID) {}
};
ReactPerf.measureMethods(ReactComponentBrowserEnvironment, 'ReactComponentBrowserEnvironment', {
replaceNodeWithMarkup: 'replaceNodeWithMarkup'
});
module.exports = ReactComponentBrowserEnvironment;
},{"49":49,"7":7,"88":88}],35:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentEnvironment
*/
'use strict';
var invariant = _dereq_(172);
var injected = false;
var ReactComponentEnvironment = {
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*/
unmountIDFromEnvironment: null,
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkup: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function (environment) {
!!injected ? "development" !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined;
ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment;
ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup;
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
},{"172":172}],36:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactComponentWithPureRenderMixin
*/
'use strict';
var shallowCompare = _dereq_(151);
/**
* If your React component's render function is "pure", e.g. it will render the
* same result given the same props and state, provide this mixin for a
* considerable performance boost.
*
* Most React components have pure render functions.
*
* Example:
*
* var ReactComponentWithPureRenderMixin =
* require('ReactComponentWithPureRenderMixin');
* React.createClass({
* mixins: [ReactComponentWithPureRenderMixin],
*
* render: function() {
* return <div className={this.props.className}>foo</div>;
* }
* });
*
* Note: This only checks shallow equality for props and state. If these contain
* complex data structures this mixin may have false-negatives for deeper
* differences. Only mixin to components which have simple props and state, or
* use `forceUpdate()` when you know deep data structures have changed.
*/
var ReactComponentWithPureRenderMixin = {
shouldComponentUpdate: function (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
};
module.exports = ReactComponentWithPureRenderMixin;
},{"151":151}],37:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCompositeComponent
*/
'use strict';
var ReactComponentEnvironment = _dereq_(35);
var ReactCurrentOwner = _dereq_(38);
var ReactElement = _dereq_(65);
var ReactErrorUtils = _dereq_(68);
var ReactInstanceMap = _dereq_(75);
var ReactInstrumentation = _dereq_(76);
var ReactNodeTypes = _dereq_(85);
var ReactPerf = _dereq_(88);
var ReactPropTypeLocations = _dereq_(90);
var ReactPropTypeLocationNames = _dereq_(89);
var ReactReconciler = _dereq_(93);
var ReactUpdateQueue = _dereq_(103);
var assign = _dereq_(24);
var emptyObject = _dereq_(165);
var invariant = _dereq_(172);
var shouldUpdateReactComponent = _dereq_(152);
var warning = _dereq_(182);
function getDeclarationErrorAddendum(component) {
var owner = component._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
var element = Component(this.props, this.context, this.updater);
warnIfInvalidElement(Component, element);
return element;
};
function warnIfInvalidElement(Component, element) {
if ("development" !== 'production') {
"development" !== 'production' ? warning(element === null || element === false || ReactElement.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : undefined;
}
}
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function (element) {
this._currentElement = element;
this._rootNodeID = null;
this._instance = null;
this._nativeParent = null;
this._nativeContainerInfo = null;
// See ReactUpdateQueue
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedNodeType = null;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} nativeParent
* @param {?object} nativeContainerInfo
* @param {?object} context
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) {
this._context = context;
this._mountOrder = nextMountID++;
this._nativeParent = nativeParent;
this._nativeContainerInfo = nativeContainerInfo;
var publicProps = this._processProps(this._currentElement.props);
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
// Initialize the public class
var inst;
var renderedElement;
if (Component.prototype && Component.prototype.isReactComponent) {
if ("development" !== 'production') {
ReactCurrentOwner.current = this;
try {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
}
} else {
if ("development" !== 'production') {
ReactCurrentOwner.current = this;
try {
inst = Component(publicProps, publicContext, ReactUpdateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
inst = Component(publicProps, publicContext, ReactUpdateQueue);
}
if (inst == null || inst.render == null) {
renderedElement = inst;
warnIfInvalidElement(Component, renderedElement);
!(inst === null || inst === false || ReactElement.isValidElement(inst)) ? "development" !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : invariant(false) : undefined;
inst = new StatelessComponent(Component);
}
}
if ("development" !== 'production') {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
"development" !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : undefined;
}
var propsMutated = inst.props !== publicProps;
var componentName = Component.displayName || Component.name || 'Component';
"development" !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : undefined;
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = ReactUpdateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if ("development" !== 'production') {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
"development" !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined;
"development" !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined;
"development" !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined;
"development" !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined;
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
var markup;
if (inst.unstable_handleError) {
markup = this.performInitialMountWithErrorHandling(renderedElement, nativeParent, nativeContainerInfo, transaction, context);
} else {
markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context);
}
if (inst.componentDidMount) {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
return markup;
},
performInitialMountWithErrorHandling: function (renderedElement, nativeParent, nativeContainerInfo, transaction, context) {
var markup;
var checkpoint = transaction.checkpoint();
try {
markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context);
} catch (e) {
// Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint
transaction.rollback(checkpoint);
this._instance.unstable_handleError(e);
if (this._pendingStateQueue) {
this._instance.state = this._processPendingState(this._instance.props, this._instance.context);
}
checkpoint = transaction.checkpoint();
this._renderedComponent.unmountComponent(true);
transaction.rollback(checkpoint);
// Try again - we've informed the component about the error, so they can render an error message this time.
// If this throws again, the error will bubble up (and can be caught by a higher error boundary).
markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context);
}
return markup;
},
performInitialMount: function (renderedElement, nativeParent, nativeContainerInfo, transaction, context) {
var inst = this._instance;
if (inst.componentWillMount) {
inst.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
this._renderedNodeType = ReactNodeTypes.getType(renderedElement);
this._renderedComponent = this._instantiateReactComponent(renderedElement);
var markup = ReactReconciler.mountComponent(this._renderedComponent, transaction, nativeParent, nativeContainerInfo, this._processChildContext(context));
return markup;
},
getNativeNode: function () {
return ReactReconciler.getNativeNode(this._renderedComponent);
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (safely) {
if (!this._renderedComponent) {
return;
}
var inst = this._instance;
if (inst.componentWillUnmount) {
if (safely) {
var name = this.getName() + '.componentWillUnmount()';
ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst));
} else {
inst.componentWillUnmount();
}
}
if (this._renderedComponent) {
ReactReconciler.unmountComponent(this._renderedComponent, safely);
this._renderedNodeType = null;
this._renderedComponent = null;
this._instance = null;
}
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = null;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function (context) {
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function (context) {
var maskedContext = this._maskContext(context);
if ("development" !== 'production') {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function (currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onBeginProcessingChildContext();
}
var childContext = inst.getChildContext && inst.getChildContext();
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onEndProcessingChildContext();
}
if (childContext) {
!(typeof Component.childContextTypes === 'object') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
if ("development" !== 'production') {
this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext);
}
for (var name in childContext) {
!(name in Component.childContextTypes) ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined;
}
return assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function (newProps) {
if ("development" !== 'production') {
var Component = this._currentElement.type;
if (Component.propTypes) {
this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop);
}
}
return newProps;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function (propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.getName();
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// top-level render calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
if (location === ReactPropTypeLocations.prop) {
// Preface gives us something to blacklist in warning module
"development" !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined;
} else {
"development" !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined;
}
}
}
}
},
receiveComponent: function (nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context);
}
if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
var willReceive = false;
var nextContext;
var nextProps;
// Determine if the context has changed or not
if (this._context === nextUnmaskedContext) {
nextContext = inst.context;
} else {
nextContext = this._processContext(nextUnmaskedContext);
willReceive = true;
}
// Distinguish between a props update versus a simple state update
if (prevParentElement === nextParentElement) {
// Skip checking prop types again -- we don't read inst.props to avoid
// warning for DOM component props in this upgrade
nextProps = nextParentElement.props;
} else {
nextProps = this._processProps(nextParentElement.props);
willReceive = true;
}
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (willReceive && inst.componentWillReceiveProps) {
inst.componentWillReceiveProps(nextProps, nextContext);
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if ("development" !== 'production') {
"development" !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined;
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var inst = this._instance;
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
var prevProps;
var prevState;
var prevContext;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
prevContext = inst.context;
}
if (inst.componentWillUpdate) {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function (transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
} else {
var oldNativeNode = ReactReconciler.getNativeNode(prevComponentInstance);
ReactReconciler.unmountComponent(prevComponentInstance, false);
this._renderedNodeType = ReactNodeTypes.getType(nextRenderedElement);
this._renderedComponent = this._instantiateReactComponent(nextRenderedElement);
var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, transaction, this._nativeParent, this._nativeContainerInfo, this._processChildContext(context));
this._replaceNodeWithMarkup(oldNativeNode, nextMarkup);
}
},
/**
* Overridden in shallow rendering.
*
* @protected
*/
_replaceNodeWithMarkup: function (oldNativeNode, nextMarkup) {
ReactComponentEnvironment.replaceNodeWithMarkup(oldNativeNode, nextMarkup);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
var renderedComponent = inst.render();
if ("development" !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (renderedComponent === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedComponent = null;
}
}
return renderedComponent;
},
/**
* @private
*/
_renderValidatedComponent: function () {
var renderedComponent;
ReactCurrentOwner.current = this;
try {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
!(
// TODO: An `isValidNode` function would probably be more appropriate
renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? "development" !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
return renderedComponent;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function (ref, component) {
var inst = this.getPublicInstance();
!(inst != null) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined;
var publicComponentInstance = component.getPublicInstance();
if ("development" !== 'production') {
var componentName = component && component.getName ? component.getName() : 'a component';
"development" !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function (ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function () {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function () {
var inst = this._instance;
if (inst instanceof StatelessComponent) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent',
_renderValidatedComponent: '_renderValidatedComponent'
});
var ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
},{"103":103,"152":152,"165":165,"172":172,"182":182,"24":24,"35":35,"38":38,"65":65,"68":68,"75":75,"76":76,"85":85,"88":88,"89":89,"90":90,"93":93}],38:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactCurrentOwner
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],39:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOM
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var ReactDOMComponentTree = _dereq_(43);
var ReactDefaultInjection = _dereq_(62);
var ReactMount = _dereq_(81);
var ReactPerf = _dereq_(88);
var ReactReconciler = _dereq_(93);
var ReactUpdates = _dereq_(104);
var ReactVersion = _dereq_(105);
var findDOMNode = _dereq_(131);
var getNativeComponentFromComposite = _dereq_(139);
var renderSubtreeIntoContainer = _dereq_(148);
var warning = _dereq_(182);
ReactDefaultInjection.inject();
var render = ReactPerf.measure('React', 'render', ReactMount.render);
var React = {
findDOMNode: findDOMNode,
render: render,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
version: ReactVersion,
/* eslint-disable camelcase */
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
/* eslint-enable camelcase */
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
ComponentTree: {
getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode,
getNodeFromInstance: function (inst) {
// inst is an internal instance (but could be a composite)
if (inst._renderedComponent) {
inst = getNativeComponentFromComposite(inst);
}
if (inst) {
return ReactDOMComponentTree.getNodeFromInstance(inst);
} else {
return null;
}
}
},
Mount: ReactMount,
Reconciler: ReactReconciler
});
}
if ("development" !== 'production') {
var ExecutionEnvironment = _dereq_(158);
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
// Firefox does not have the issue with devtools loaded over file://
var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1;
console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools');
}
}
var testFunc = function testFn() {};
"development" !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : undefined;
// If we're in IE8, check to see if we are in compatibility mode and provide
// information on preventing compatibility mode
var ieCompatibilityMode = document.documentMode && document.documentMode < 8;
"development" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined;
var expectedFeatures = [
// shims
Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
"development" !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : undefined;
break;
}
}
}
}
module.exports = React;
},{"104":104,"105":105,"131":131,"139":139,"148":148,"158":158,"182":182,"43":43,"62":62,"81":81,"88":88,"93":93}],40:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMButton
*/
'use strict';
var mouseListenerNames = {
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
};
/**
* Implements a <button> native component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = {
getNativeProps: function (inst, props) {
if (!props.disabled) {
return props;
}
// Copy the props, except the mouse listeners
var nativeProps = {};
for (var key in props) {
if (props.hasOwnProperty(key) && !mouseListenerNames[key]) {
nativeProps[key] = props[key];
}
}
return nativeProps;
}
};
module.exports = ReactDOMButton;
},{}],41:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponent
*/
/* global hasOwnProperty:true */
'use strict';
var AutoFocusUtils = _dereq_(1);
var CSSPropertyOperations = _dereq_(4);
var DOMLazyTree = _dereq_(8);
var DOMNamespaces = _dereq_(9);
var DOMProperty = _dereq_(10);
var DOMPropertyOperations = _dereq_(11);
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(16);
var EventPluginRegistry = _dereq_(17);
var ReactBrowserEventEmitter = _dereq_(27);
var ReactComponentBrowserEnvironment = _dereq_(34);
var ReactDOMButton = _dereq_(40);
var ReactDOMComponentFlags = _dereq_(42);
var ReactDOMComponentTree = _dereq_(43);
var ReactDOMInput = _dereq_(50);
var ReactDOMOption = _dereq_(52);
var ReactDOMSelect = _dereq_(53);
var ReactDOMTextarea = _dereq_(57);
var ReactMultiChild = _dereq_(82);
var ReactPerf = _dereq_(88);
var assign = _dereq_(24);
var escapeTextContentForBrowser = _dereq_(130);
var invariant = _dereq_(172);
var isEventSupported = _dereq_(144);
var keyOf = _dereq_(176);
var shallowEqual = _dereq_(181);
var validateDOMNesting = _dereq_(155);
var warning = _dereq_(182);
var Flags = ReactDOMComponentFlags;
var deleteListener = EventPluginHub.deleteListener;
var getNode = ReactDOMComponentTree.getNodeFromInstance;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = EventPluginRegistry.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = { 'string': true, 'number': true };
var CHILDREN = keyOf({ children: null });
var STYLE = keyOf({ style: null });
var HTML = keyOf({ __html: null });
function getDeclarationErrorAddendum(internalInstance) {
if (internalInstance) {
var owner = internalInstance._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' This DOM node was rendered by `' + name + '`.';
}
}
}
return '';
}
function friendlyStringify(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return '[' + obj.map(friendlyStringify).join(', ') + ']';
} else {
var pairs = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
}
}
return '{' + pairs.join(', ') + '}';
}
} else if (typeof obj === 'string') {
return JSON.stringify(obj);
} else if (typeof obj === 'function') {
return '[function object]';
}
// Differs from JSON.stringify in that undefined because undefined and that
// inf and nan don't become null
return String(obj);
}
var styleMutationWarning = {};
function checkAndWarnForMutatedStyle(style1, style2, component) {
if (style1 == null || style2 == null) {
return;
}
if (shallowEqual(style1, style2)) {
return;
}
var componentName = component._tag;
var owner = component._currentElement._owner;
var ownerName;
if (owner) {
ownerName = owner.getName();
}
var hash = ownerName + '|' + componentName;
if (styleMutationWarning.hasOwnProperty(hash)) {
return;
}
styleMutationWarning[hash] = true;
"development" !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined;
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (voidElementTags[component._tag]) {
!(props.children == null && props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : invariant(false) : undefined;
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? "development" !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined;
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? "development" !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined;
}
if ("development" !== 'production') {
"development" !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined;
"development" !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined;
}
!(props.style == null || typeof props.style === 'object') ? "development" !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined;
}
function enqueuePutListener(inst, registrationName, listener, transaction) {
if ("development" !== 'production') {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
"development" !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined;
}
var containerInfo = inst._nativeContainerInfo;
var doc = containerInfo._ownerDocument;
if (!doc) {
// Server rendering.
return;
}
listenTo(registrationName, doc);
transaction.getReactMountReady().enqueue(putListener, {
inst: inst,
registrationName: registrationName,
listener: listener
});
}
function putListener() {
var listenerToPut = this;
EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener);
}
// There are so many media events, it makes sense to just
// maintain a list rather than create a `trapBubbledEvent` for each
var mediaEvents = {
topAbort: 'abort',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topSeeked: 'seeked',
topSeeking: 'seeking',
topStalled: 'stalled',
topSuspend: 'suspend',
topTimeUpdate: 'timeupdate',
topVolumeChange: 'volumechange',
topWaiting: 'waiting'
};
function trapBubbledEventsLocal() {
var inst = this;
// If a component renders to null or if another component fatals and causes
// the state of the tree to be corrupted, `node` here can be null.
!inst._rootNodeID ? "development" !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined;
var node = getNode(inst);
!node ? "development" !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined;
switch (inst._tag) {
case 'iframe':
case 'object':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'video':
case 'audio':
inst._wrapperState.listeners = [];
// Create listener for each media event
for (var event in mediaEvents) {
if (mediaEvents.hasOwnProperty(event)) {
inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node));
}
}
break;
case 'img':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'form':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)];
break;
case 'input':
case 'select':
case 'textarea':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, 'invalid', node)];
break;
}
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special-case tags.
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
};
// NOTE: menuitem's close tag should be omitted, but that causes problems.
var newlineEatingTags = {
'listing': true,
'pre': true,
'textarea': true
};
// For HTML, certain tags cannot have children. This has the same purpose as
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags = assign({
'menuitem': true
}, omittedCloseTags);
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
var hasOwnProperty = {}.hasOwnProperty;
function validateDangerousTag(tag) {
if (!hasOwnProperty.call(validatedTagCache, tag)) {
!VALID_TAG_REGEX.test(tag) ? "development" !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined;
validatedTagCache[tag] = true;
}
}
function isCustomComponent(tagName, props) {
return tagName.indexOf('-') >= 0 || props.is != null;
}
var globalIdCounter = 1;
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(element) {
var tag = element.type;
validateDangerousTag(tag);
this._currentElement = element;
this._tag = tag.toLowerCase();
this._namespaceURI = null;
this._renderedChildren = null;
this._previousStyle = null;
this._previousStyleCopy = null;
this._nativeNode = null;
this._nativeParent = null;
this._rootNodeID = null;
this._domID = null;
this._nativeContainerInfo = null;
this._wrapperState = null;
this._topLevelWrapper = null;
this._flags = 0;
if ("development" !== 'production') {
this._ancestorInfo = null;
}
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?ReactDOMComponent} the containing DOM component instance
* @param {?object} info about the native container
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) {
this._rootNodeID = globalIdCounter++;
this._domID = nativeContainerInfo._idCounter++;
this._nativeParent = nativeParent;
this._nativeContainerInfo = nativeContainerInfo;
var props = this._currentElement.props;
switch (this._tag) {
case 'iframe':
case 'object':
case 'img':
case 'form':
case 'video':
case 'audio':
this._wrapperState = {
listeners: null
};
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'button':
props = ReactDOMButton.getNativeProps(this, props, nativeParent);
break;
case 'input':
ReactDOMInput.mountWrapper(this, props, nativeParent);
props = ReactDOMInput.getNativeProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'option':
ReactDOMOption.mountWrapper(this, props, nativeParent);
props = ReactDOMOption.getNativeProps(this, props);
break;
case 'select':
ReactDOMSelect.mountWrapper(this, props, nativeParent);
props = ReactDOMSelect.getNativeProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'textarea':
ReactDOMTextarea.mountWrapper(this, props, nativeParent);
props = ReactDOMTextarea.getNativeProps(this, props);
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
}
assertValidProps(this, props);
// We create tags in the namespace of their parent container, except HTML
// tags get no namespace.
var namespaceURI;
var parentTag;
if (nativeParent != null) {
namespaceURI = nativeParent._namespaceURI;
parentTag = nativeParent._tag;
} else if (nativeContainerInfo._tag) {
namespaceURI = nativeContainerInfo._namespaceURI;
parentTag = nativeContainerInfo._tag;
}
if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') {
namespaceURI = DOMNamespaces.html;
}
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'svg') {
namespaceURI = DOMNamespaces.svg;
} else if (this._tag === 'math') {
namespaceURI = DOMNamespaces.mathml;
}
}
this._namespaceURI = namespaceURI;
if ("development" !== 'production') {
var parentInfo;
if (nativeParent != null) {
parentInfo = nativeParent._ancestorInfo;
} else if (nativeContainerInfo._tag) {
parentInfo = nativeContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting(this._tag, this, parentInfo);
}
this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this);
}
var mountImage;
if (transaction.useCreateElement) {
var ownerDocument = nativeContainerInfo._ownerDocument;
var el;
if (namespaceURI === DOMNamespaces.html) {
if (this._tag === 'script') {
// Create the script via .innerHTML so its "parser-inserted" flag is
// set to true and it does not execute
var div = ownerDocument.createElement('div');
var type = this._currentElement.type;
div.innerHTML = '<' + type + '></' + type + '>';
el = div.removeChild(div.firstChild);
} else {
el = ownerDocument.createElement(this._currentElement.type);
}
} else {
el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type);
}
ReactDOMComponentTree.precacheNode(this, el);
this._flags |= Flags.hasCachedChildNodes;
if (!this._nativeParent) {
DOMPropertyOperations.setAttributeForRoot(el);
}
this._updateDOMProperties(null, props, transaction);
var lazyTree = DOMLazyTree(el);
this._createInitialChildren(transaction, props, context, lazyTree);
mountImage = lazyTree;
} else {
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
var tagContent = this._createContentMarkup(transaction, props, context);
if (!tagContent && omittedCloseTags[this._tag]) {
mountImage = tagOpen + '/>';
} else {
mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>';
}
}
switch (this._tag) {
case 'button':
case 'input':
case 'select':
case 'textarea':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
}
return mountImage;
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function (transaction, props) {
var ret = '<' + this._currentElement.type;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
if (propValue) {
enqueuePutListener(this, propKey, propValue, transaction);
}
} else {
if (propKey === STYLE) {
if (propValue) {
if ("development" !== 'production') {
// See `_updateDOMProperties`. style block
this._previousStyle = propValue;
}
propValue = this._previousStyleCopy = assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this);
}
var markup = null;
if (this._tag != null && isCustomComponent(this._tag, props)) {
if (propKey !== CHILDREN) {
markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret;
}
if (!this._nativeParent) {
ret += ' ' + DOMPropertyOperations.createMarkupForRoot();
}
ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID);
return ret;
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function (transaction, props, context) {
var ret = '';
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
ret = innerHTML.__html;
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
ret = escapeTextContentForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
ret = mountImages.join('');
}
}
if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
return '\n' + ret;
} else {
return ret;
}
},
_createInitialChildren: function (transaction, props, context, lazyTree) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
DOMLazyTree.queueHTML(lazyTree, innerHTML.__html);
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
DOMLazyTree.queueText(lazyTree, contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
for (var i = 0; i < mountImages.length; i++) {
DOMLazyTree.queueChild(lazyTree, mountImages[i]);
}
}
}
},
/**
* Receives a next element and updates the component.
*
* @internal
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
*/
receiveComponent: function (nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'button':
lastProps = ReactDOMButton.getNativeProps(this, lastProps);
nextProps = ReactDOMButton.getNativeProps(this, nextProps);
break;
case 'input':
ReactDOMInput.updateWrapper(this);
lastProps = ReactDOMInput.getNativeProps(this, lastProps);
nextProps = ReactDOMInput.getNativeProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getNativeProps(this, lastProps);
nextProps = ReactDOMOption.getNativeProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getNativeProps(this, lastProps);
nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
lastProps = ReactDOMTextarea.getNativeProps(this, lastProps);
nextProps = ReactDOMTextarea.getNativeProps(this, nextProps);
break;
}
assertValidProps(this, nextProps);
this._updateDOMProperties(lastProps, nextProps, transaction);
this._updateDOMChildren(lastProps, nextProps, transaction, context);
if (this._tag === 'select') {
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
}
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {object} nextProps
* @param {?DOMElement} node
*/
_updateDOMProperties: function (lastProps, nextProps, transaction) {
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
continue;
}
if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
this._previousStyleCopy = null;
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (lastProps[propKey]) {
// Only call deleteListener if there was a listener previously or
// else willDeleteListener gets called when there wasn't actually a
// listener (e.g., onClick={null})
deleteListener(this, propKey);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined;
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
if ("development" !== 'production') {
checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this);
this._previousStyle = nextProp;
}
nextProp = this._previousStyleCopy = assign({}, nextProp);
} else {
this._previousStyleCopy = null;
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (nextProp) {
enqueuePutListener(this, propKey, nextProp, transaction);
} else if (lastProp) {
deleteListener(this, propKey);
}
} else if (isCustomComponent(this._tag, nextProps)) {
if (propKey === CHILDREN) {
nextProp = null;
}
DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp);
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
var node = getNode(this);
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertently setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (nextProp != null) {
DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
} else {
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
}
if (styleUpdates) {
CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {object} context
*/
_updateDOMChildren: function (lastProps, nextProps, transaction, context) {
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html;
var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction, context);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
this.updateMarkup('' + nextHtml);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction, context);
}
},
getNativeNode: function () {
return getNode(this);
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function (safely) {
switch (this._tag) {
case 'iframe':
case 'object':
case 'img':
case 'form':
case 'video':
case 'audio':
var listeners = this._wrapperState.listeners;
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].remove();
}
}
break;
case 'html':
case 'head':
case 'body':
/**
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*/
!false ? "development" !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined;
break;
}
this.unmountChildren(safely);
ReactDOMComponentTree.uncacheNode(this);
EventPluginHub.deleteAllListeners(this);
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._domID = null;
this._wrapperState = null;
},
getPublicInstance: function () {
return getNode(this);
}
};
ReactPerf.measureMethods(ReactDOMComponent.Mixin, 'ReactDOMComponent', {
mountComponent: 'mountComponent',
receiveComponent: 'receiveComponent'
});
assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
},{"1":1,"10":10,"11":11,"130":130,"144":144,"15":15,"155":155,"16":16,"17":17,"172":172,"176":176,"181":181,"182":182,"24":24,"27":27,"34":34,"4":4,"40":40,"42":42,"43":43,"50":50,"52":52,"53":53,"57":57,"8":8,"82":82,"88":88,"9":9}],42:[function(_dereq_,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponentFlags
*/
'use strict';
var ReactDOMComponentFlags = {
hasCachedChildNodes: 1 << 0
};
module.exports = ReactDOMComponentFlags;
},{}],43:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMComponentTree
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactDOMComponentFlags = _dereq_(42);
var invariant = _dereq_(172);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var Flags = ReactDOMComponentFlags;
var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2);
/**
* Drill down (through composites and empty components) until we get a native or
* native text component.
*
* This is pretty polymorphic but unavoidable with the current structure we have
* for `_renderedChildren`.
*/
function getRenderedNativeOrTextFromComponent(component) {
var rendered;
while (rendered = component._renderedComponent) {
component = rendered;
}
return component;
}
/**
* Populate `_nativeNode` on the rendered native/text component with the given
* DOM node. The passed `inst` can be a composite.
*/
function precacheNode(inst, node) {
var nativeInst = getRenderedNativeOrTextFromComponent(inst);
nativeInst._nativeNode = node;
node[internalInstanceKey] = nativeInst;
}
function uncacheNode(inst) {
var node = inst._nativeNode;
if (node) {
delete node[internalInstanceKey];
inst._nativeNode = null;
}
}
/**
* Populate `_nativeNode` on each child of `inst`, assuming that the children
* match up with the DOM (element) children of `node`.
*
* We cache entire levels at once to avoid an n^2 problem where we access the
* children of a node sequentially and have to walk from the start to our target
* node every time.
*
* Since we update `_renderedChildren` and the actual DOM at (slightly)
* different times, we could race here and see a newer `_renderedChildren` than
* the DOM nodes we see. To avoid this, ReactMultiChild calls
* `prepareToManageChildren` before we change `_renderedChildren`, at which
* time the container's child nodes are always cached (until it unmounts).
*/
function precacheChildNodes(inst, node) {
if (inst._flags & Flags.hasCachedChildNodes) {
return;
}
var children = inst._renderedChildren;
var childNode = node.firstChild;
outer: for (var name in children) {
if (!children.hasOwnProperty(name)) {
continue;
}
var childInst = children[name];
var childID = getRenderedNativeOrTextFromComponent(childInst)._domID;
if (childID == null) {
// We're currently unmounting this child in ReactMultiChild; skip it.
continue;
}
// We assume the child nodes are in the same order as the child instances.
for (; childNode !== null; childNode = childNode.nextSibling) {
if (childNode.nodeType === 1 && childNode.getAttribute(ATTR_NAME) === String(childID) || childNode.nodeType === 8 && childNode.nodeValue === ' react-text: ' + childID + ' ' || childNode.nodeType === 8 && childNode.nodeValue === ' react-empty: ' + childID + ' ') {
precacheNode(childInst, childNode);
continue outer;
}
}
// We reached the end of the DOM children without finding an ID match.
!false ? "development" !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : invariant(false) : undefined;
}
inst._flags |= Flags.hasCachedChildNodes;
}
/**
* Given a DOM node, return the closest ReactDOMComponent or
* ReactDOMTextComponent instance ancestor.
*/
function getClosestInstanceFromNode(node) {
if (node[internalInstanceKey]) {
return node[internalInstanceKey];
}
// Walk up the tree until we find an ancestor whose instance we have cached.
var parents = [];
while (!node[internalInstanceKey]) {
parents.push(node);
if (node.parentNode) {
node = node.parentNode;
} else {
// Top of the tree. This node must not be part of a React tree (or is
// unmounted, potentially).
return null;
}
}
var closest;
var inst;
for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) {
closest = inst;
if (parents.length) {
precacheChildNodes(inst, node);
}
}
return closest;
}
/**
* Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
* instance, or null if the node was not rendered by this React.
*/
function getInstanceFromNode(node) {
var inst = getClosestInstanceFromNode(node);
if (inst != null && inst._nativeNode === node) {
return inst;
} else {
return null;
}
}
/**
* Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
* DOM node.
*/
function getNodeFromInstance(inst) {
// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
!(inst._nativeNode !== undefined) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : undefined;
if (inst._nativeNode) {
return inst._nativeNode;
}
// Walk up the tree until we find an ancestor whose DOM node we have cached.
var parents = [];
while (!inst._nativeNode) {
parents.push(inst);
!inst._nativeParent ? "development" !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : invariant(false) : undefined;
inst = inst._nativeParent;
}
// Now parents contains each ancestor that does *not* have a cached native
// node, and `inst` is the deepest ancestor that does.
for (; parents.length; inst = parents.pop()) {
precacheChildNodes(inst, inst._nativeNode);
}
return inst._nativeNode;
}
var ReactDOMComponentTree = {
getClosestInstanceFromNode: getClosestInstanceFromNode,
getInstanceFromNode: getInstanceFromNode,
getNodeFromInstance: getNodeFromInstance,
precacheChildNodes: precacheChildNodes,
precacheNode: precacheNode,
uncacheNode: uncacheNode
};
module.exports = ReactDOMComponentTree;
},{"10":10,"172":172,"42":42}],44:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMContainerInfo
*/
'use strict';
var validateDOMNesting = _dereq_(155);
var DOC_NODE_TYPE = 9;
function ReactDOMContainerInfo(topLevelWrapper, node) {
var info = {
_topLevelWrapper: topLevelWrapper,
_idCounter: 1,
_ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null,
_tag: node ? node.nodeName.toLowerCase() : null,
_namespaceURI: node ? node.namespaceURI : null
};
if ("development" !== 'production') {
info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null;
}
return info;
}
module.exports = ReactDOMContainerInfo;
},{"155":155}],45:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMDebugTool
*/
'use strict';
var ReactDOMUnknownPropertyDevtool = _dereq_(59);
var warning = _dereq_(182);
var eventHandlers = [];
var handlerDoesThrowForEvent = {};
function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
if ("development" !== 'production') {
eventHandlers.forEach(function (handler) {
try {
if (handler[handlerFunctionName]) {
handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5);
}
} catch (e) {
"development" !== 'production' ? warning(!handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e.message) : undefined;
handlerDoesThrowForEvent[handlerFunctionName] = true;
}
});
}
}
var ReactDOMDebugTool = {
addDevtool: function (devtool) {
eventHandlers.push(devtool);
},
removeDevtool: function (devtool) {
for (var i = 0; i < eventHandlers.length; i++) {
if (eventHandlers[i] === devtool) {
eventHandlers.splice(i, 1);
i--;
}
}
},
onCreateMarkupForProperty: function (name, value) {
emitEvent('onCreateMarkupForProperty', name, value);
},
onSetValueForProperty: function (node, name, value) {
emitEvent('onSetValueForProperty', node, name, value);
},
onDeleteValueForProperty: function (node, name) {
emitEvent('onDeleteValueForProperty', node, name);
}
};
ReactDOMDebugTool.addDevtool(ReactDOMUnknownPropertyDevtool);
module.exports = ReactDOMDebugTool;
},{"182":182,"59":59}],46:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMEmptyComponent
*/
'use strict';
var DOMLazyTree = _dereq_(8);
var ReactDOMComponentTree = _dereq_(43);
var assign = _dereq_(24);
var ReactDOMEmptyComponent = function (instantiate) {
// ReactCompositeComponent uses this:
this._currentElement = null;
// ReactDOMComponentTree uses these:
this._nativeNode = null;
this._nativeParent = null;
this._nativeContainerInfo = null;
this._domID = null;
};
assign(ReactDOMEmptyComponent.prototype, {
mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) {
var domID = nativeContainerInfo._idCounter++;
this._domID = domID;
this._nativeParent = nativeParent;
this._nativeContainerInfo = nativeContainerInfo;
var nodeValue = ' react-empty: ' + this._domID + ' ';
if (transaction.useCreateElement) {
var ownerDocument = nativeContainerInfo._ownerDocument;
var node = ownerDocument.createComment(nodeValue);
ReactDOMComponentTree.precacheNode(this, node);
return DOMLazyTree(node);
} else {
if (transaction.renderToStaticMarkup) {
// Normally we'd insert a comment node, but since this is a situation
// where React won't take over (static pages), we can simply return
// nothing.
return '';
}
return '<!--' + nodeValue + '-->';
}
},
receiveComponent: function () {},
getNativeNode: function () {
return ReactDOMComponentTree.getNodeFromInstance(this);
},
unmountComponent: function () {
ReactDOMComponentTree.uncacheNode(this);
}
});
module.exports = ReactDOMEmptyComponent;
},{"24":24,"43":43,"8":8}],47:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMFactories
*/
'use strict';
var ReactElement = _dereq_(65);
var ReactElementValidator = _dereq_(66);
var mapObject = _dereq_(177);
/**
* Create a factory that creates HTML tag elements.
*
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMFactory(tag) {
if ("development" !== 'production') {
return ReactElementValidator.createFactory(tag);
}
return ReactElement.createFactory(tag);
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOMFactories = mapObject({
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',
// SVG
circle: 'circle',
clipPath: 'clipPath',
defs: 'defs',
ellipse: 'ellipse',
g: 'g',
image: 'image',
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'
}, createDOMFactory);
module.exports = ReactDOMFactories;
},{"177":177,"65":65,"66":66}],48:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMFeatureFlags
*/
'use strict';
var ReactDOMFeatureFlags = {
useCreateElement: true
};
module.exports = ReactDOMFeatureFlags;
},{}],49:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMIDOperations
*/
'use strict';
var DOMChildrenOperations = _dereq_(7);
var ReactDOMComponentTree = _dereq_(43);
var ReactPerf = _dereq_(88);
/**
* Operations used to process updates to DOM nodes.
*/
var ReactDOMIDOperations = {
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @internal
*/
dangerouslyProcessChildrenUpdates: function (parentInst, updates) {
var node = ReactDOMComponentTree.getNodeFromInstance(parentInst);
DOMChildrenOperations.processUpdates(node, updates);
}
};
ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', {
dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates'
});
module.exports = ReactDOMIDOperations;
},{"43":43,"7":7,"88":88}],50:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMInput
*/
'use strict';
var DOMPropertyOperations = _dereq_(11);
var LinkedValueUtils = _dereq_(23);
var ReactDOMComponentTree = _dereq_(43);
var ReactUpdates = _dereq_(104);
var assign = _dereq_(24);
var invariant = _dereq_(172);
var warning = _dereq_(182);
var didWarnValueLink = false;
var didWarnCheckedLink = false;
var didWarnValueNull = false;
var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
}
function warnIfValueIsNull(props) {
if (props != null && props.value === null && !didWarnValueNull) {
"development" !== 'production' ? warning(false, '`value` prop on `input` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : undefined;
didWarnValueNull = true;
}
}
/**
* Implements an <input> native component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = {
getNativeProps: function (inst, props) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var nativeProps = assign({
// Make sure we set .type before any other properties (setting .value
// before .type means .value is lost in IE11 and below)
type: undefined
}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if ("development" !== 'production') {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
"development" !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : undefined;
didWarnValueLink = true;
}
if (props.checkedLink !== undefined && !didWarnCheckedLink) {
"development" !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : undefined;
didWarnCheckedLink = true;
}
if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
"development" !== 'production' ? warning(false, 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : undefined;
didWarnCheckedDefaultChecked = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
"development" !== 'production' ? warning(false, 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : undefined;
didWarnValueDefaultValue = true;
}
warnIfValueIsNull(props);
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.defaultChecked || false,
initialValue: defaultValue != null ? defaultValue : null,
listeners: null,
onChange: _handleChange.bind(inst)
};
if ("development" !== 'production') {
inst._wrapperState.controlled = props.checked !== undefined || props.value !== undefined;
}
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
if ("development" !== 'production') {
warnIfValueIsNull(props);
var initialValue = inst._wrapperState.initialChecked || inst._wrapperState.initialValue;
var defaultValue = props.defaultChecked || props.defaultValue;
var controlled = props.checked !== undefined || props.value !== undefined;
var owner = inst._currentElement._owner;
if ((initialValue || !inst._wrapperState.controlled) && controlled && !didWarnUncontrolledToControlled) {
"development" !== 'production' ? warning(false, '%s is changing a uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : undefined;
didWarnUncontrolledToControlled = true;
}
if (inst._wrapperState.controlled && (defaultValue || !controlled) && !didWarnControlledToUncontrolled) {
"development" !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or viceversa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : undefined;
didWarnControlledToUncontrolled = true;
}
}
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
if (checked != null) {
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false);
}
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactDOMComponentTree.getNodeFromInstance(this);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React radio buttons with non-React ones.
var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode);
!otherInstance ? "development" !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined;
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
module.exports = ReactDOMInput;
},{"104":104,"11":11,"172":172,"182":182,"23":23,"24":24,"43":43}],51:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMInstrumentation
*/
'use strict';
var ReactDOMDebugTool = _dereq_(45);
module.exports = { debugTool: ReactDOMDebugTool };
},{"45":45}],52:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMOption
*/
'use strict';
var ReactChildren = _dereq_(31);
var ReactDOMSelect = _dereq_(53);
var assign = _dereq_(24);
var warning = _dereq_(182);
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = {
mountWrapper: function (inst, props, nativeParent) {
// TODO (yungsters): Remove support for `selected` in <option>.
if ("development" !== 'production') {
"development" !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined;
}
// Look up whether this option is 'selected'
var selectValue = null;
if (nativeParent != null && nativeParent._tag === 'select') {
selectValue = ReactDOMSelect.getSelectValueContext(nativeParent);
}
// If the value is null (e.g., no specified value or after initial mount)
// or missing (e.g., for <datalist>), we don't change props.selected
var selected = null;
if (selectValue != null) {
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) {
if ('' + selectValue[i] === '' + props.value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === '' + props.value;
}
}
inst._wrapperState = { selected: selected };
},
getNativeProps: function (inst, props) {
var nativeProps = assign({ selected: undefined, children: undefined }, props);
// Read state only from initial mount because <select> updates value
// manually; we need the initial state only for server rendering
if (inst._wrapperState.selected != null) {
nativeProps.selected = inst._wrapperState.selected;
}
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
ReactChildren.forEach(props.children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else {
"development" !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined;
}
});
if (content) {
nativeProps.children = content;
}
return nativeProps;
}
};
module.exports = ReactDOMOption;
},{"182":182,"24":24,"31":31,"53":53}],53:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelect
*/
'use strict';
var LinkedValueUtils = _dereq_(23);
var ReactDOMComponentTree = _dereq_(43);
var ReactUpdates = _dereq_(104);
var assign = _dereq_(24);
var warning = _dereq_(182);
var didWarnValueLink = false;
var didWarnValueNull = false;
var didWarnValueDefaultValue = false;
function updateOptionsIfPendingUpdateAndMounted() {
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
this._wrapperState.pendingUpdate = false;
var props = this._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
updateOptions(this, Boolean(props.multiple), value);
}
}
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
function warnIfValueIsNull(props) {
if (props != null && props.value === null && !didWarnValueNull) {
"development" !== 'production' ? warning(false, '`value` prop on `select` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : undefined;
didWarnValueNull = true;
}
}
var valuePropNames = ['value', 'defaultValue'];
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function checkSelectPropTypes(inst, props) {
var owner = inst._currentElement._owner;
LinkedValueUtils.checkPropTypes('select', props, owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
"development" !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : undefined;
didWarnValueLink = true;
}
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
if (props.multiple) {
"development" !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
} else {
"development" !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
}
}
}
/**
* @param {ReactDOMComponent} inst
* @param {boolean} multiple
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(inst, multiple, propValue) {
var selectedValue, i;
var options = ReactDOMComponentTree.getNodeFromInstance(inst).options;
if (multiple) {
selectedValue = {};
for (i = 0; i < propValue.length; i++) {
selectedValue['' + propValue[i]] = true;
}
for (i = 0; i < options.length; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
if (options[i].selected !== selected) {
options[i].selected = selected;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
selectedValue = '' + propValue;
for (i = 0; i < options.length; i++) {
if (options[i].value === selectedValue) {
options[i].selected = true;
return;
}
}
if (options.length) {
options[0].selected = true;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = {
getNativeProps: function (inst, props) {
return assign({}, props, {
onChange: inst._wrapperState.onChange,
value: undefined
});
},
mountWrapper: function (inst, props) {
if ("development" !== 'production') {
checkSelectPropTypes(inst, props);
warnIfValueIsNull(props);
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
pendingUpdate: false,
initialValue: value != null ? value : props.defaultValue,
listeners: null,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
};
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
"development" !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : undefined;
didWarnValueDefaultValue = true;
}
},
getSelectValueContext: function (inst) {
// ReactDOMOption looks at this initial value so the initial generated
// markup has correct `selected` attributes
return inst._wrapperState.initialValue;
},
postUpdateWrapper: function (inst) {
var props = inst._currentElement.props;
if ("development" !== 'production') {
warnIfValueIsNull(props);
}
// After the initial mount, we control selected-ness manually so don't pass
// this value down
inst._wrapperState.initialValue = undefined;
var wasMultiple = inst._wrapperState.wasMultiple;
inst._wrapperState.wasMultiple = Boolean(props.multiple);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
inst._wrapperState.pendingUpdate = false;
updateOptions(inst, Boolean(props.multiple), value);
} else if (wasMultiple !== Boolean(props.multiple)) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (props.defaultValue != null) {
updateOptions(inst, Boolean(props.multiple), props.defaultValue);
} else {
// Revert the select back to its default unselected state.
updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
}
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
if (this._rootNodeID) {
this._wrapperState.pendingUpdate = true;
}
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
module.exports = ReactDOMSelect;
},{"104":104,"182":182,"23":23,"24":24,"43":43}],54:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMSelection
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
var getNodeForCharacterOffset = _dereq_(140);
var getTextContentAccessor = _dereq_(141);
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// In Firefox, range.startContainer and range.endContainer can be "anonymous
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
// divs do not seem to expose properties, triggering a "Permission denied
// error" if any of its properties are accessed. The only seemingly possible
// way to avoid erroring is to access a property that typically works for
// non-anonymous divs and catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
currentRange.startContainer.nodeType;
currentRange.endContainer.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (offsets.end === undefined) {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programmatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = offsets.end === undefined ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window);
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
},{"140":140,"141":141,"158":158}],55:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMServer
*/
'use strict';
var ReactDefaultInjection = _dereq_(62);
var ReactServerRendering = _dereq_(96);
var ReactVersion = _dereq_(105);
ReactDefaultInjection.inject();
var ReactDOMServer = {
renderToString: ReactServerRendering.renderToString,
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
version: ReactVersion
};
module.exports = ReactDOMServer;
},{"105":105,"62":62,"96":96}],56:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextComponent
*/
'use strict';
var DOMChildrenOperations = _dereq_(7);
var DOMLazyTree = _dereq_(8);
var ReactDOMComponentTree = _dereq_(43);
var ReactPerf = _dereq_(88);
var assign = _dereq_(24);
var escapeTextContentForBrowser = _dereq_(130);
var invariant = _dereq_(172);
var validateDOMNesting = _dereq_(155);
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings between comment nodes so that they
* can undergo the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// ReactDOMComponentTree uses these:
this._nativeNode = null;
this._nativeParent = null;
// Properties
this._domID = null;
this._mountIndex = 0;
this._closingComment = null;
this._commentNodes = null;
};
assign(ReactDOMTextComponent.prototype, {
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) {
if ("development" !== 'production') {
var parentInfo;
if (nativeParent != null) {
parentInfo = nativeParent._ancestorInfo;
} else if (nativeContainerInfo != null) {
parentInfo = nativeContainerInfo._ancestorInfo;
}
if (parentInfo) {
// parentInfo should always be present except for the top-level
// component when server rendering
validateDOMNesting('#text', this, parentInfo);
}
}
var domID = nativeContainerInfo._idCounter++;
var openingValue = ' react-text: ' + domID + ' ';
var closingValue = ' /react-text ';
this._domID = domID;
this._nativeParent = nativeParent;
if (transaction.useCreateElement) {
var ownerDocument = nativeContainerInfo._ownerDocument;
var openingComment = ownerDocument.createComment(openingValue);
var closingComment = ownerDocument.createComment(closingValue);
var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment());
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment));
if (this._stringText) {
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText)));
}
DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment));
ReactDOMComponentTree.precacheNode(this, openingComment);
this._closingComment = closingComment;
return lazyTree;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this between comment nodes for the reasons stated
// above, but since this is a situation where React won't take over
// (static pages), we can simply return the text as it is.
return escapedText;
}
return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->';
}
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function (nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var commentNodes = this.getNativeNode();
DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText);
}
}
},
getNativeNode: function () {
var nativeNode = this._commentNodes;
if (nativeNode) {
return nativeNode;
}
if (!this._closingComment) {
var openingComment = ReactDOMComponentTree.getNodeFromInstance(this);
var node = openingComment.nextSibling;
while (true) {
!(node != null) ? "development" !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : invariant(false) : undefined;
if (node.nodeType === 8 && node.nodeValue === ' /react-text ') {
this._closingComment = node;
break;
}
node = node.nextSibling;
}
}
nativeNode = [this._nativeNode, this._closingComment];
this._commentNodes = nativeNode;
return nativeNode;
},
unmountComponent: function () {
this._closingComment = null;
this._commentNodes = null;
ReactDOMComponentTree.uncacheNode(this);
}
});
ReactPerf.measureMethods(ReactDOMTextComponent.prototype, 'ReactDOMTextComponent', {
mountComponent: 'mountComponent',
receiveComponent: 'receiveComponent'
});
module.exports = ReactDOMTextComponent;
},{"130":130,"155":155,"172":172,"24":24,"43":43,"7":7,"8":8,"88":88}],57:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTextarea
*/
'use strict';
var DOMPropertyOperations = _dereq_(11);
var LinkedValueUtils = _dereq_(23);
var ReactDOMComponentTree = _dereq_(43);
var ReactUpdates = _dereq_(104);
var assign = _dereq_(24);
var invariant = _dereq_(172);
var warning = _dereq_(182);
var didWarnValueLink = false;
var didWarnValueNull = false;
var didWarnValDefaultVal = false;
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
}
function warnIfValueIsNull(props) {
if (props != null && props.value === null && !didWarnValueNull) {
"development" !== 'production' ? warning(false, '`value` prop on `textarea` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : undefined;
didWarnValueNull = true;
}
}
/**
* Implements a <textarea> native component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = {
getNativeProps: function (inst, props) {
!(props.dangerouslySetInnerHTML == null) ? "development" !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
var nativeProps = assign({}, props, {
defaultValue: undefined,
value: undefined,
children: inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if ("development" !== 'production') {
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
if (props.valueLink !== undefined && !didWarnValueLink) {
"development" !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : undefined;
didWarnValueLink = true;
}
if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
"development" !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : undefined;
didWarnValDefaultVal = true;
}
warnIfValueIsNull(props);
}
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = props.children;
if (children != null) {
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined;
}
!(defaultValue == null) ? "development" !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined;
if (Array.isArray(children)) {
!(children.length <= 1) ? "development" !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined;
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: '' + (value != null ? value : defaultValue),
listeners: null,
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
if ("development" !== 'production') {
warnIfValueIsNull(props);
}
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
module.exports = ReactDOMTextarea;
},{"104":104,"11":11,"172":172,"182":182,"23":23,"24":24,"43":43}],58:[function(_dereq_,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMTreeTraversal
*/
'use strict';
var invariant = _dereq_(172);
/**
* Return the lowest common ancestor of A and B, or null if they are in
* different trees.
*/
function getLowestCommonAncestor(instA, instB) {
!('_nativeNode' in instA) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : undefined;
!('_nativeNode' in instB) ? "development" !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : undefined;
var depthA = 0;
for (var tempA = instA; tempA; tempA = tempA._nativeParent) {
depthA++;
}
var depthB = 0;
for (var tempB = instB; tempB; tempB = tempB._nativeParent) {
depthB++;
}
// If A is deeper, crawl up.
while (depthA - depthB > 0) {
instA = instA._nativeParent;
depthA--;
}
// If B is deeper, crawl up.
while (depthB - depthA > 0) {
instB = instB._nativeParent;
depthB--;
}
// Walk in lockstep until we find a match.
var depth = depthA;
while (depth--) {
if (instA === instB) {
return instA;
}
instA = instA._nativeParent;
instB = instB._nativeParent;
}
return null;
}
/**
* Return if A is an ancestor of B.
*/
function isAncestor(instA, instB) {
!('_nativeNode' in instA) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : invariant(false) : undefined;
!('_nativeNode' in instB) ? "development" !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : invariant(false) : undefined;
while (instB) {
if (instB === instA) {
return true;
}
instB = instB._nativeParent;
}
return false;
}
/**
* Return the parent instance of the passed-in instance.
*/
function getParentInstance(inst) {
!('_nativeNode' in inst) ? "development" !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : invariant(false) : undefined;
return inst._nativeParent;
}
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*/
function traverseTwoPhase(inst, fn, arg) {
var path = [];
while (inst) {
path.push(inst);
inst = inst._nativeParent;
}
var i;
for (i = path.length; i-- > 0;) {
fn(path[i], false, arg);
}
for (i = 0; i < path.length; i++) {
fn(path[i], true, arg);
}
}
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* Does not invoke the callback on the nearest common ancestor because nothing
* "entered" or "left" that element.
*/
function traverseEnterLeave(from, to, fn, argFrom, argTo) {
var common = from && to ? getLowestCommonAncestor(from, to) : null;
var pathFrom = [];
while (from && from !== common) {
pathFrom.push(from);
from = from._nativeParent;
}
var pathTo = [];
while (to && to !== common) {
pathTo.push(to);
to = to._nativeParent;
}
var i;
for (i = 0; i < pathFrom.length; i++) {
fn(pathFrom[i], true, argFrom);
}
for (i = pathTo.length; i-- > 0;) {
fn(pathTo[i], false, argTo);
}
}
module.exports = {
isAncestor: isAncestor,
getLowestCommonAncestor: getLowestCommonAncestor,
getParentInstance: getParentInstance,
traverseTwoPhase: traverseTwoPhase,
traverseEnterLeave: traverseEnterLeave
};
},{"172":172}],59:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDOMUnknownPropertyDevtool
*/
'use strict';
var DOMProperty = _dereq_(10);
var EventPluginRegistry = _dereq_(17);
var warning = _dereq_(182);
if ("development" !== 'production') {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function (name) {
if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) {
return;
}
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
"development" !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined;
var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null;
"development" !== 'production' ? warning(registrationName == null, 'Unknown event handler property %s. Did you mean `%s`?', name, registrationName) : undefined;
};
}
var ReactDOMUnknownPropertyDevtool = {
onCreateMarkupForProperty: function (name, value) {
warnUnknownProperty(name);
},
onSetValueForProperty: function (node, name, value) {
warnUnknownProperty(name);
},
onDeleteValueForProperty: function (node, name) {
warnUnknownProperty(name);
}
};
module.exports = ReactDOMUnknownPropertyDevtool;
},{"10":10,"17":17,"182":182}],60:[function(_dereq_,module,exports){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDebugTool
*/
'use strict';
var ReactInvalidSetStateWarningDevTool = _dereq_(77);
var warning = _dereq_(182);
var eventHandlers = [];
var handlerDoesThrowForEvent = {};
function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
if ("development" !== 'production') {
eventHandlers.forEach(function (handler) {
try {
if (handler[handlerFunctionName]) {
handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5);
}
} catch (e) {
"development" !== 'production' ? warning(!handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e.message) : undefined;
handlerDoesThrowForEvent[handlerFunctionName] = true;
}
});
}
}
var ReactDebugTool = {
addDevtool: function (devtool) {
eventHandlers.push(devtool);
},
removeDevtool: function (devtool) {
for (var i = 0; i < eventHandlers.length; i++) {
if (eventHandlers[i] === devtool) {
eventHandlers.splice(i, 1);
i--;
}
}
},
onBeginProcessingChildContext: function () {
emitEvent('onBeginProcessingChildContext');
},
onEndProcessingChildContext: function () {
emitEvent('onEndProcessingChildContext');
},
onSetState: function () {
emitEvent('onSetState');
},
onMountRootComponent: function (internalInstance) {
emitEvent('onMountRootComponent', internalInstance);
},
onMountComponent: function (internalInstance) {
emitEvent('onMountComponent', internalInstance);
},
onUpdateComponent: function (internalInstance) {
emitEvent('onUpdateComponent', internalInstance);
},
onUnmountComponent: function (internalInstance) {
emitEvent('onUnmountComponent', internalInstance);
}
};
ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool);
module.exports = ReactDebugTool;
},{"182":182,"77":77}],61:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultBatchingStrategy
*/
'use strict';
var ReactUpdates = _dereq_(104);
var Transaction = _dereq_(123);
var assign = _dereq_(24);
var emptyFunction = _dereq_(164);
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function () {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d, e);
} else {
transaction.perform(callback, null, a, b, c, d, e);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"104":104,"123":123,"164":164,"24":24}],62:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultInjection
*/
'use strict';
var BeforeInputEventPlugin = _dereq_(2);
var ChangeEventPlugin = _dereq_(6);
var DefaultEventPluginOrder = _dereq_(13);
var EnterLeaveEventPlugin = _dereq_(14);
var ExecutionEnvironment = _dereq_(158);
var HTMLDOMPropertyConfig = _dereq_(21);
var ReactComponentBrowserEnvironment = _dereq_(34);
var ReactDOMComponent = _dereq_(41);
var ReactDOMComponentTree = _dereq_(43);
var ReactDOMEmptyComponent = _dereq_(46);
var ReactDOMTreeTraversal = _dereq_(58);
var ReactDOMTextComponent = _dereq_(56);
var ReactDefaultBatchingStrategy = _dereq_(61);
var ReactEventListener = _dereq_(70);
var ReactInjection = _dereq_(73);
var ReactReconcileTransaction = _dereq_(92);
var SVGDOMPropertyConfig = _dereq_(107);
var SelectEventPlugin = _dereq_(108);
var SimpleEventPlugin = _dereq_(109);
var alreadyInjected = false;
function inject() {
if (alreadyInjected) {
// TODO: This is currently true because these injections are shared between
// the client and the server package. They should be built independently
// and not share any injection state. Then this problem will be solved.
return;
}
alreadyInjected = true;
ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree);
ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent);
ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) {
return new ReactDOMEmptyComponent(instantiate);
});
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if ("development" !== 'production') {
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
if (/[?&]react_perf\b/.test(url)) {
var ReactDefaultPerf = _dereq_(63);
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
},{"107":107,"108":108,"109":109,"13":13,"14":14,"158":158,"2":2,"21":21,"34":34,"41":41,"43":43,"46":46,"56":56,"58":58,"6":6,"61":61,"63":63,"70":70,"73":73,"92":92}],63:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultPerf
*/
'use strict';
var DOMProperty = _dereq_(10);
var ReactDOMComponentTree = _dereq_(43);
var ReactDefaultPerfAnalysis = _dereq_(64);
var ReactMount = _dereq_(81);
var ReactPerf = _dereq_(88);
var performanceNow = _dereq_(180);
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
function addValue(obj, key, val) {
obj[key] = (obj[key] || 0) + val;
}
// Composite/text components don't have any built-in ID: we have to make our own
var compositeIDMap;
var compositeIDCounter = 17000;
function getIDOfComposite(inst) {
if (!compositeIDMap) {
compositeIDMap = new WeakMap();
}
if (compositeIDMap.has(inst)) {
return compositeIDMap.get(inst);
} else {
var id = compositeIDCounter++;
compositeIDMap.set(inst, id);
return id;
}
}
function getID(inst) {
if (inst.hasOwnProperty('_rootNodeID')) {
return inst._rootNodeID;
} else {
return getIDOfComposite(inst);
}
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_mountStack: [0],
_compositeStack: [],
_injected: false,
start: function () {
if (!ReactDefaultPerf._injected) {
ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure);
}
ReactDefaultPerf._allMeasurements.length = 0;
ReactPerf.enableMeasure = true;
},
stop: function () {
ReactPerf.enableMeasure = false;
},
getLastMeasurements: function () {
return ReactDefaultPerf._allMeasurements;
},
printExclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Component class name': item.componentName,
'Total inclusive time (ms)': roundFloat(item.inclusive),
'Exclusive mount time (ms)': roundFloat(item.exclusive),
'Exclusive render time (ms)': roundFloat(item.render),
'Mount time per instance (ms)': roundFloat(item.exclusive / item.count),
'Render time per instance (ms)': roundFloat(item.render / item.count),
'Instances': item.count
};
}));
// TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct
// number.
},
printInclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Inclusive time (ms)': roundFloat(item.time),
'Instances': item.count
};
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
getMeasurementsSummaryMap: function (measurements) {
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true);
return summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
});
},
printWasted: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
printDOM: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements);
console.table(summary.map(function (item) {
var result = {};
result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id;
result.type = item.type;
result.args = JSON.stringify(item.args);
return result;
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
_recordWrite: function (id, fnName, totalTime, args) {
// TODO: totalTime isn't that useful since it doesn't count paints/reflows
var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1];
var writes = entry.writes;
writes[id] = writes[id] || [];
writes[id].push({
type: fnName,
time: totalTime,
args: args
});
},
measure: function (moduleName, fnName, func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var totalTime;
var rv;
var start;
var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1];
if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') {
// A "measurement" is a set of metrics recorded for each flush. We want
// to group the metrics for a given flush together so we can look at the
// components that rendered and the DOM operations that actually
// happened to determine the amount of "wasted work" performed.
ReactDefaultPerf._allMeasurements.push(entry = {
exclusive: {},
inclusive: {},
render: {},
counts: {},
writes: {},
displayNames: {},
hierarchy: {},
totalTime: 0,
created: {}
});
start = performanceNow();
rv = func.apply(this, args);
entry.totalTime = performanceNow() - start;
return rv;
} else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations' || moduleName === 'ReactComponentBrowserEnvironment') {
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (fnName === '_mountImageIntoNode') {
ReactDefaultPerf._recordWrite('', fnName, totalTime, args[0]);
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
// special format
args[1].forEach(function (update) {
var writeArgs = {};
if (update.fromIndex !== null) {
writeArgs.fromIndex = update.fromIndex;
}
if (update.toIndex !== null) {
writeArgs.toIndex = update.toIndex;
}
if (update.content !== null) {
writeArgs.content = update.content;
}
ReactDefaultPerf._recordWrite(args[0]._rootNodeID, update.type, totalTime, writeArgs);
});
} else {
// basic format
var id = args[0];
if (moduleName === 'EventPluginHub') {
id = id._rootNodeID;
} else if (fnName === 'replaceNodeWithMarkup') {
// Old node is already unmounted; can't get its instance
id = ReactDOMComponentTree.getInstanceFromNode(args[1].node)._rootNodeID;
} else if (fnName === 'replaceDelimitedText') {
id = getID(ReactDOMComponentTree.getInstanceFromNode(args[0]));
} else if (typeof id === 'object') {
id = getID(ReactDOMComponentTree.getInstanceFromNode(args[0]));
}
ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1));
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
if (this._currentElement.type === ReactMount.TopLevelWrapper) {
return func.apply(this, args);
}
var rootNodeID = getIDOfComposite(this);
var isRender = fnName === '_renderValidatedComponent';
var isMount = fnName === 'mountComponent';
var mountStack = ReactDefaultPerf._mountStack;
if (isRender) {
addValue(entry.counts, rootNodeID, 1);
} else if (isMount) {
entry.created[rootNodeID] = true;
mountStack.push(0);
}
ReactDefaultPerf._compositeStack.push(rootNodeID);
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
ReactDefaultPerf._compositeStack.pop();
if (isRender) {
addValue(entry.render, rootNodeID, totalTime);
} else if (isMount) {
var subMountTime = mountStack.pop();
mountStack[mountStack.length - 1] += totalTime;
addValue(entry.exclusive, rootNodeID, totalTime - subMountTime);
addValue(entry.inclusive, rootNodeID, totalTime);
} else {
addValue(entry.inclusive, rootNodeID, totalTime);
}
entry.displayNames[rootNodeID] = {
current: this.getName(),
owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>'
};
return rv;
} else if ((moduleName === 'ReactDOMComponent' || moduleName === 'ReactDOMTextComponent') && (fnName === 'mountComponent' || fnName === 'receiveComponent')) {
rv = func.apply(this, args);
entry.hierarchy[getID(this)] = ReactDefaultPerf._compositeStack.slice();
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
},{"10":10,"180":180,"43":43,"64":64,"81":81,"88":88}],64:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactDefaultPerfAnalysis
*/
'use strict';
var assign = _dereq_(24);
// Don't try to save users less than 1.2ms (a number I made up)
var DONT_CARE_THRESHOLD = 1.2;
var DOM_OPERATION_TYPES = {
'_mountImageIntoNode': 'set innerHTML',
INSERT_MARKUP: 'set innerHTML',
MOVE_EXISTING: 'move',
REMOVE_NODE: 'remove',
SET_MARKUP: 'set innerHTML',
TEXT_CONTENT: 'set textContent',
'setValueForProperty': 'update attribute',
'setValueForAttribute': 'update attribute',
'deleteValueForProperty': 'remove attribute',
'setValueForStyles': 'update styles',
'replaceNodeWithMarkup': 'replace',
'replaceDelimitedText': 'replace',
'updateTextContent': 'set textContent'
};
function getTotalTime(measurements) {
// TODO: return number of DOM ops? could be misleading.
// TODO: measure dropped frames after reconcile?
// TODO: log total time of each reconcile and the top-level component
// class that triggered it.
var totalTime = 0;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
totalTime += measurement.totalTime;
}
return totalTime;
}
function getDOMSummary(measurements) {
var items = [];
measurements.forEach(function (measurement) {
Object.keys(measurement.writes).forEach(function (id) {
measurement.writes[id].forEach(function (write) {
items.push({
id: id,
type: DOM_OPERATION_TYPES[write.type] || write.type,
args: write.args
});
});
});
});
return items;
}
function getExclusiveSummary(measurements) {
var candidates = {};
var displayName;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
displayName = measurement.displayNames[id].current;
candidates[displayName] = candidates[displayName] || {
componentName: displayName,
inclusive: 0,
exclusive: 0,
render: 0,
count: 0
};
if (measurement.render[id]) {
candidates[displayName].render += measurement.render[id];
}
if (measurement.exclusive[id]) {
candidates[displayName].exclusive += measurement.exclusive[id];
}
if (measurement.inclusive[id]) {
candidates[displayName].inclusive += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[displayName].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (displayName in candidates) {
if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) {
arr.push(candidates[displayName]);
}
}
arr.sort(function (a, b) {
return b.exclusive - a.exclusive;
});
return arr;
}
function getInclusiveSummary(measurements, onlyClean) {
var candidates = {};
var inclusiveKey;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
var cleanComponents;
if (onlyClean) {
cleanComponents = getUnchangedComponents(measurement);
}
for (var id in allIDs) {
if (onlyClean && !cleanComponents[id]) {
continue;
}
var displayName = measurement.displayNames[id];
// Inclusive time is not useful for many components without knowing where
// they are instantiated. So we aggregate inclusive time with both the
// owner and current displayName as the key.
inclusiveKey = displayName.owner + ' > ' + displayName.current;
candidates[inclusiveKey] = candidates[inclusiveKey] || {
componentName: inclusiveKey,
time: 0,
count: 0
};
if (measurement.inclusive[id]) {
candidates[inclusiveKey].time += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[inclusiveKey].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (inclusiveKey in candidates) {
if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) {
arr.push(candidates[inclusiveKey]);
}
}
arr.sort(function (a, b) {
return b.time - a.time;
});
return arr;
}
function getUnchangedComponents(measurement) {
// For a given reconcile, look at which components did not actually
// render anything to the DOM and return a mapping of their ID to
// the amount of time it took to render the entire subtree.
var cleanComponents = {};
var writes = measurement.writes;
var dirtyComposites = {};
Object.keys(writes).forEach(function (id) {
writes[id].forEach(function (write) {
// Root mounting (innerHTML set) is recorded with an ID of ''
if (id !== '') {
measurement.hierarchy[id].forEach(function (c) {
return dirtyComposites[c] = true;
});
}
});
});
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// See if any of the DOM operations applied to this component's subtree.
if (dirtyComposites[id]) {
isDirty = true;
}
// check if component newly created
if (measurement.created[id]) {
isDirty = true;
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
},{"24":24}],65:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElement
*/
'use strict';
var ReactCurrentOwner = _dereq_(38);
var assign = _dereq_(24);
var warning = _dereq_(182);
var canDefineProperty = _dereq_(127);
// The Symbol used to tag the ReactElement type. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown;
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, no instanceof check
* will work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} key
* @param {string|object} ref
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @param {*} owner
* @param {*} props
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if ("development" !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
ReactElement.createElement = function (type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if ("development" !== 'production') {
ref = !config.hasOwnProperty('ref') || Object.getOwnPropertyDescriptor(config, 'ref').get ? null : config.ref;
key = !config.hasOwnProperty('key') || Object.getOwnPropertyDescriptor(config, 'key').get ? null : '' + config.key;
} else {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if ("development" !== 'production') {
// Create dummy `key` and `ref` property to `props` to warn users
// against its use
if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {
if (!props.hasOwnProperty('key')) {
Object.defineProperty(props, 'key', {
get: function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
"development" !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element') : undefined;
}
return undefined;
},
configurable: true
});
}
if (!props.hasOwnProperty('ref')) {
Object.defineProperty(props, 'ref', {
get: function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
"development" !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element') : undefined;
}
return undefined;
},
configurable: true
});
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
ReactElement.createFactory = function (type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
};
ReactElement.cloneElement = function (element, config, children) {
var propName;
// Original props are copied
var props = assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Self is preserved since the owner is preserved.
var self = element._self;
// Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (config.ref !== undefined) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (config.key !== undefined) {
key = '' + config.key;
}
// Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
};
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
module.exports = ReactElement;
},{"127":127,"182":182,"24":24,"38":38}],66:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactElement = _dereq_(65);
var ReactPropTypeLocations = _dereq_(90);
var ReactPropTypeLocationNames = _dereq_(89);
var ReactCurrentOwner = _dereq_(38);
var canDefineProperty = _dereq_(127);
var getIteratorFn = _dereq_(138);
var invariant = _dereq_(172);
var warning = _dereq_(182);
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
var loggedTypeFailures = {};
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var addenda = getAddendaForKeyUse('uniqueKey', element, parentType);
if (addenda === null) {
// we already showed the warning
return;
}
"development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined;
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} messageType A key used for de-duping warnings.
* @param {ReactElement} element Component that requires a key.
* @param {*} parentType element's parent's type.
* @returns {?object} A set of addenda to use in the warning message, or null
* if the warning has already been shown before (and shouldn't be shown again).
*/
function getAddendaForKeyUse(messageType, element, parentType) {
var addendum = getDeclarationErrorAddendum();
if (!addendum) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
addendum = ' Check the top-level render call using <' + parentName + '>.';
}
}
var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {});
if (memoizer[addendum]) {
return null;
}
memoizer[addendum] = true;
var addenda = {
parentOrOwner: addendum,
url: ' See https://fb.me/react-warning-keys for more information.',
childOwner: null
};
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
return addenda;
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Assert that the props are valid
*
* @param {string} componentName Name of the component for error messages.
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
"development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var addendum = getDeclarationErrorAddendum();
"development" !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined;
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
var componentClass = element.type;
if (typeof componentClass !== 'function') {
return;
}
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop);
}
if (typeof componentClass.getDefaultProps === 'function') {
"development" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined;
}
}
var ReactElementValidator = {
createElement: function (type, props, children) {
var validType = typeof type === 'string' || typeof type === 'function';
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
"development" !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined;
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
validatePropTypes(element);
return element;
},
createFactory: function (type) {
var validatedFactory = ReactElementValidator.createElement.bind(null, type);
// Legacy hook TODO: Warn if this is accessed
validatedFactory.type = type;
if ("development" !== 'production') {
if (canDefineProperty) {
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
"development" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined;
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
}
return validatedFactory;
},
cloneElement: function (element, props, children) {
var newElement = ReactElement.cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
};
module.exports = ReactElementValidator;
},{"127":127,"138":138,"172":172,"182":182,"38":38,"65":65,"89":89,"90":90}],67:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponent
*/
'use strict';
var emptyComponentFactory;
var ReactEmptyComponentInjection = {
injectEmptyComponentFactory: function (factory) {
emptyComponentFactory = factory;
}
};
var ReactEmptyComponent = {
create: function (instantiate) {
return emptyComponentFactory(instantiate);
}
};
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
},{}],68:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactErrorUtils
*/
'use strict';
var caughtError = null;
/**
* Call a function while guarding against errors that happens within it.
*
* @param {?String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} a First argument
* @param {*} b Second argument
*/
function invokeGuardedCallback(name, func, a, b) {
try {
return func(a, b);
} catch (x) {
if (caughtError === null) {
caughtError = x;
}
return undefined;
}
}
var ReactErrorUtils = {
invokeGuardedCallback: invokeGuardedCallback,
/**
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
* handler are sure to be rethrown by rethrowCaughtError.
*/
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
rethrowCaughtError: function () {
if (caughtError) {
var error = caughtError;
caughtError = null;
throw error;
}
}
};
if ("development" !== 'production') {
/**
* To help development we can get better devtools integration by simulating a
* real browser event.
*/
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
var fakeNode = document.createElement('react');
ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
var boundFunc = func.bind(null, a, b);
var evtType = 'react-' + name;
fakeNode.addEventListener(evtType, boundFunc, false);
var evt = document.createEvent('Event');
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
fakeNode.removeEventListener(evtType, boundFunc, false);
};
}
}
module.exports = ReactErrorUtils;
},{}],69:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventEmitterMixin
*/
'use strict';
var EventPluginHub = _dereq_(16);
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue(false);
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*/
handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
},{"16":16}],70:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEventListener
*/
'use strict';
var EventListener = _dereq_(157);
var ExecutionEnvironment = _dereq_(158);
var PooledClass = _dereq_(25);
var ReactDOMComponentTree = _dereq_(43);
var ReactUpdates = _dereq_(104);
var assign = _dereq_(24);
var getEventTarget = _dereq_(137);
var getUnboundedScrollPosition = _dereq_(169);
/**
* Find the deepest React component completely containing the root of the
* passed-in instance (for use when entire React trees are nested within each
* other). If React trees are not nested, returns null.
*/
function findParent(inst) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
while (inst._nativeParent) {
inst = inst._nativeParent;
}
var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst);
var container = rootNode.parentNode;
return ReactDOMComponentTree.getClosestInstanceFromNode(container);
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function () {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
function handleTopLevelImpl(bookKeeping) {
var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent);
var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget);
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = targetInst;
do {
bookKeeping.ancestors.push(ancestor);
ancestor = ancestor && findParent(ancestor);
} while (ancestor);
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
targetInst = bookKeeping.ancestors[i];
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function (handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function (enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function () {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
monitorScrollValue: function (refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function (topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
},{"104":104,"137":137,"157":157,"158":158,"169":169,"24":24,"25":25,"43":43}],71:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactFeatureFlags
*/
'use strict';
var ReactFeatureFlags = {
// When true, call console.time() before and .timeEnd() after each top-level
// render (both initial renders and updates). Useful when looking at prod-mode
// timeline profiles in Chrome, for example.
logTopLevelRenders: false
};
module.exports = ReactFeatureFlags;
},{}],72:[function(_dereq_,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactFragment
*/
'use strict';
var ReactChildren = _dereq_(31);
var ReactElement = _dereq_(65);
var emptyFunction = _dereq_(164);
var invariant = _dereq_(172);
var warning = _dereq_(182);
/**
* We used to allow keyed objects to serve as a collection of ReactElements,
* or nested sets. This allowed us a way to explicitly key a set or fragment of
* components. This is now being replaced with an opaque data structure.
* The upgrade path is to call React.addons.createFragment({ key: value }) to
* create a keyed fragment. The resulting data structure is an array.
*/
var numericPropertyRegex = /^\d+$/;
var warnedAboutNumeric = false;
var ReactFragment = {
// Wrap a keyed object in an opaque proxy that warns you if you access any
// of its properties.
create: function (object) {
if (typeof object !== 'object' || !object || Array.isArray(object)) {
"development" !== 'production' ? warning(false, 'React.addons.createFragment only accepts a single object. Got: %s', object) : undefined;
return object;
}
if (ReactElement.isValidElement(object)) {
"development" !== 'production' ? warning(false, 'React.addons.createFragment does not accept a ReactElement ' + 'without a wrapper object.') : undefined;
return object;
}
!(object.nodeType !== 1) ? "development" !== 'production' ? invariant(false, 'React.addons.createFragment(...): Encountered an invalid child; DOM ' + 'elements are not valid children of React components.') : invariant(false) : undefined;
var result = [];
for (var key in object) {
if ("development" !== 'production') {
if (!warnedAboutNumeric && numericPropertyRegex.test(key)) {
"development" !== 'production' ? warning(false, 'React.addons.createFragment(...): Child objects should have ' + 'non-numeric keys so ordering is preserved.') : undefined;
warnedAboutNumeric = true;
}
}
ReactChildren.mapIntoWithKeyPrefixInternal(object[key], result, key, emptyFunction.thatReturnsArgument);
}
return result;
}
};
module.exports = ReactFragment;
},{"164":164,"172":172,"182":182,"31":31,"65":65}],73:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInjection
*/
'use strict';
var DOMProperty = _dereq_(10);
var EventPluginHub = _dereq_(16);
var EventPluginUtils = _dereq_(18);
var ReactComponentEnvironment = _dereq_(35);
var ReactClass = _dereq_(32);
var ReactEmptyComponent = _dereq_(67);
var ReactBrowserEventEmitter = _dereq_(27);
var ReactNativeComponent = _dereq_(84);
var ReactPerf = _dereq_(88);
var ReactUpdates = _dereq_(104);
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventPluginUtils: EventPluginUtils.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Perf: ReactPerf.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"10":10,"104":104,"16":16,"18":18,"27":27,"32":32,"35":35,"67":67,"84":84,"88":88}],74:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInputSelection
*/
'use strict';
var ReactDOMSelection = _dereq_(54);
var containsNode = _dereq_(161);
var focusNode = _dereq_(166);
var getActiveElement = _dereq_(167);
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function (elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true');
},
getSelectionInformation: function () {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function (priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function (input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || { start: 0, end: 0 };
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function (input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (end === undefined) {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
},{"161":161,"166":166,"167":167,"54":54}],75:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstanceMap
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function (key) {
key._reactInternalInstance = undefined;
},
get: function (key) {
return key._reactInternalInstance;
},
has: function (key) {
return key._reactInternalInstance !== undefined;
},
set: function (key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
},{}],76:[function(_dereq_,module,exports){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInstrumentation
*/
'use strict';
var ReactDebugTool = _dereq_(60);
module.exports = { debugTool: ReactDebugTool };
},{"60":60}],77:[function(_dereq_,module,exports){
/**
* Copyright 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInvalidSetStateWarningDevTool
*/
'use strict';
var warning = _dereq_(182);
if ("development" !== 'production') {
var processingChildContext = false;
var warnInvalidSetState = function () {
"development" !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : undefined;
};
}
var ReactInvalidSetStateWarningDevTool = {
onBeginProcessingChildContext: function () {
processingChildContext = true;
},
onEndProcessingChildContext: function () {
processingChildContext = false;
},
onSetState: function () {
warnInvalidSetState();
}
};
module.exports = ReactInvalidSetStateWarningDevTool;
},{"182":182}],78:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactIsomorphic
*/
'use strict';
var ReactChildren = _dereq_(31);
var ReactComponent = _dereq_(33);
var ReactClass = _dereq_(32);
var ReactDOMFactories = _dereq_(47);
var ReactElement = _dereq_(65);
var ReactElementValidator = _dereq_(66);
var ReactPropTypes = _dereq_(91);
var ReactVersion = _dereq_(105);
var assign = _dereq_(24);
var onlyChild = _dereq_(146);
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if ("development" !== 'production') {
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactComponent,
createElement: createElement,
cloneElement: cloneElement,
isValidElement: ReactElement.isValidElement,
// Classic
PropTypes: ReactPropTypes,
createClass: ReactClass.createClass,
createFactory: createFactory,
createMixin: function (mixin) {
// Currently a noop. Will be used to validate and trace mixins.
return mixin;
},
// This looks DOM specific but these are actually isomorphic helpers
// since they are just generating DOM strings.
DOM: ReactDOMFactories,
version: ReactVersion,
// Hook for JSX spread, don't use this for anything else.
__spread: assign
};
module.exports = React;
},{"105":105,"146":146,"24":24,"31":31,"32":32,"33":33,"47":47,"65":65,"66":66,"91":91}],79:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactLink
*/
'use strict';
/**
* ReactLink encapsulates a common pattern in which a component wants to modify
* a prop received from its parent. ReactLink allows the parent to pass down a
* value coupled with a callback that, when invoked, expresses an intent to
* modify that value. For example:
*
* React.createClass({
* getInitialState: function() {
* return {value: ''};
* },
* render: function() {
* var valueLink = new ReactLink(this.state.value, this._handleValueChange);
* return <input valueLink={valueLink} />;
* },
* _handleValueChange: function(newValue) {
* this.setState({value: newValue});
* }
* });
*
* We have provided some sugary mixins to make the creation and
* consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin.
*/
var React = _dereq_(26);
/**
* @param {*} value current value of the link
* @param {function} requestChange callback to request a change
*/
function ReactLink(value, requestChange) {
this.value = value;
this.requestChange = requestChange;
}
/**
* Creates a PropType that enforces the ReactLink API and optionally checks the
* type of the value being passed inside the link. Example:
*
* MyComponent.propTypes = {
* tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number)
* }
*/
function createLinkTypeChecker(linkType) {
var shapes = {
value: linkType === undefined ? React.PropTypes.any.isRequired : linkType.isRequired,
requestChange: React.PropTypes.func.isRequired
};
return React.PropTypes.shape(shapes);
}
ReactLink.PropTypes = {
link: createLinkTypeChecker
};
module.exports = ReactLink;
},{"26":26}],80:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMarkupChecksum
*/
'use strict';
var adler32 = _dereq_(126);
var TAG_END = /\/?>/;
var COMMENT_START = /^<\!\-\-/;
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function (markup) {
var checksum = adler32(markup);
// Add checksum (handle both parent tags, comments and self-closing tags)
if (COMMENT_START.test(markup)) {
return markup;
} else {
return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
}
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function (markup, element) {
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
},{"126":126}],81:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMount
*/
'use strict';
var DOMLazyTree = _dereq_(8);
var DOMProperty = _dereq_(10);
var ReactBrowserEventEmitter = _dereq_(27);
var ReactCurrentOwner = _dereq_(38);
var ReactDOMComponentTree = _dereq_(43);
var ReactDOMContainerInfo = _dereq_(44);
var ReactDOMFeatureFlags = _dereq_(48);
var ReactElement = _dereq_(65);
var ReactFeatureFlags = _dereq_(71);
var ReactInstrumentation = _dereq_(76);
var ReactMarkupChecksum = _dereq_(80);
var ReactPerf = _dereq_(88);
var ReactReconciler = _dereq_(93);
var ReactUpdateQueue = _dereq_(103);
var ReactUpdates = _dereq_(104);
var emptyObject = _dereq_(165);
var instantiateReactComponent = _dereq_(143);
var invariant = _dereq_(172);
var setInnerHTML = _dereq_(149);
var shouldUpdateReactComponent = _dereq_(152);
var warning = _dereq_(182);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME;
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
var instancesByReactRootID = {};
/**
* Finds the index of the first character
* that's not common between the two given strings.
*
* @return {number} the index of the character where the strings diverge
*/
function firstDifferenceIndex(string1, string2) {
var minLen = Math.min(string1.length, string2.length);
for (var i = 0; i < minLen; i++) {
if (string1.charAt(i) !== string2.charAt(i)) {
return i;
}
}
return string1.length === string2.length ? -1 : minLen;
}
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) {
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var wrappedElement = wrapperInstance._currentElement.props;
var type = wrappedElement.type;
markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name);
console.time(markerName);
}
var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context);
if (markerName) {
console.timeEnd(markerName);
}
wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance;
ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */
!shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement);
transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
function unmountComponentFromNode(instance, container, safely) {
ReactReconciler.unmountComponent(instance, safely);
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
}
/**
* True if the supplied DOM node has a direct React-rendered child that is
* not a React root element. Useful for warning in `render`,
* `unmountComponentAtNode`, etc.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM element contains a direct child that was
* rendered by React but is not a root element.
* @internal
*/
function hasNonRootReactChild(container) {
var rootEl = getReactRootElementInContainer(container);
if (rootEl) {
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
return !!(inst && inst._nativeParent);
}
}
function getNativeRootInstanceInContainer(container) {
var rootEl = getReactRootElementInContainer(container);
var prevNativeInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
return prevNativeInstance && !prevNativeInstance._nativeParent ? prevNativeInstance : null;
}
function getTopLevelWrapperInContainer(container) {
var root = getNativeRootInstanceInContainer(container);
return root ? root._nativeContainerInfo._topLevelWrapper : null;
}
/**
* Temporary (?) hack so that we can store all top-level pending updates on
* composites instead of having to worry about different types of components
* here.
*/
var topLevelRootCounter = 1;
var TopLevelWrapper = function () {
this.rootID = topLevelRootCounter++;
};
TopLevelWrapper.prototype.isReactComponent = {};
if ("development" !== 'production') {
TopLevelWrapper.displayName = 'TopLevelWrapper';
}
TopLevelWrapper.prototype.render = function () {
// this.props is actually a ReactElement
return this.props;
};
/**
* Mounting is the process of initializing a React component by creating its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.render(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
TopLevelWrapper: TopLevelWrapper,
/**
* Used by devtools. The keys are not important.
*/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function (container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactElement} nextElement component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function (prevComponent, nextElement, container, callback) {
ReactMount.scrollMonitor(container, function () {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
return prevComponent;
},
/**
* Render a new component into the DOM. Hooked by devtools!
*
* @param {ReactElement} nextElement element to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
"development" !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var componentInstance = instantiateReactComponent(nextElement);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context);
var wrapperID = componentInstance._instance.rootID;
instancesByReactRootID[wrapperID] = componentInstance;
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onMountRootComponent(componentInstance);
}
return componentInstance;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} parentComponent The conceptual parent of this render tree.
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!(parentComponent != null && parentComponent._reactInternalInstance != null) ? "development" !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined;
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
},
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!ReactElement.isValidElement(nextElement) ? "development" !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined;
"development" !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined;
var nextWrappedElement = ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement);
var prevComponent = getTopLevelWrapperInContainer(container);
if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement;
var prevElement = prevWrappedElement.props;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
var publicInst = prevComponent._renderedComponent.getPublicInstance();
var updatedCallback = callback && function () {
callback.call(publicInst);
};
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback);
return publicInst;
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
var containerHasNonRootReactChild = hasNonRootReactChild(container);
if ("development" !== 'production') {
"development" !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined;
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
var rootElementSibling = reactRootElement;
while (rootElementSibling) {
if (internalGetID(rootElementSibling)) {
"development" !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined;
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
render: function (nextElement, container, callback) {
return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function (container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
"development" !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined;
var prevComponent = getTopLevelWrapperInContainer(container);
if (!prevComponent) {
// Check if the node being unmounted was rendered by React, but isn't a
// root node.
var containerHasNonRootReactChild = hasNonRootReactChild(container);
// Check if the container itself is a React root node.
var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME);
if ("development" !== 'production') {
"development" !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined;
}
return false;
}
delete instancesByReactRootID[prevComponent._instance.rootID];
ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false);
return true;
},
_mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) {
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? "development" !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined;
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
ReactDOMComponentTree.precacheNode(instance, rootElement);
return;
} else {
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
var normalizedMarkup = markup;
if ("development" !== 'production') {
// because rootMarkup is retrieved from the DOM, various normalizations
// will have occurred which will not be present in `markup`. Here,
// insert markup into a <div> or <iframe> depending on the container
// type to perform the same normalizations before comparing.
var normalizer;
if (container.nodeType === ELEMENT_NODE_TYPE) {
normalizer = document.createElement('div');
normalizer.innerHTML = markup;
normalizedMarkup = normalizer.innerHTML;
} else {
normalizer = document.createElement('iframe');
document.body.appendChild(normalizer);
normalizer.contentDocument.write(markup);
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
document.body.removeChild(normalizer);
}
}
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
!(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined;
}
}
}
!(container.nodeType !== DOC_NODE_TYPE) ? "development" !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
if (transaction.useCreateElement) {
while (container.lastChild) {
container.removeChild(container.lastChild);
}
DOMLazyTree.insertTreeBefore(container, markup, null);
} else {
setInnerHTML(container, markup);
ReactDOMComponentTree.precacheNode(instance, container.firstChild);
}
}
};
ReactPerf.measureMethods(ReactMount, 'ReactMount', {
_renderNewRootComponent: '_renderNewRootComponent',
_mountImageIntoNode: '_mountImageIntoNode'
});
module.exports = ReactMount;
},{"10":10,"103":103,"104":104,"143":143,"149":149,"152":152,"165":165,"172":172,"182":182,"27":27,"38":38,"43":43,"44":44,"48":48,"65":65,"71":71,"76":76,"8":8,"80":80,"88":88,"93":93}],82:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChild
*/
'use strict';
var ReactComponentEnvironment = _dereq_(35);
var ReactMultiChildUpdateTypes = _dereq_(83);
var ReactCurrentOwner = _dereq_(38);
var ReactReconciler = _dereq_(93);
var ReactChildReconciler = _dereq_(30);
var flattenChildren = _dereq_(132);
var invariant = _dereq_(172);
/**
* Make an update for markup to be rendered and inserted at a supplied index.
*
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function makeInsertMarkup(markup, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for moving an existing element to another index.
*
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function makeMove(child, afterNode, toIndex) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
content: null,
fromIndex: child._mountIndex,
fromNode: ReactReconciler.getNativeNode(child),
toIndex: toIndex,
afterNode: afterNode
};
}
/**
* Make an update for removing an element at an index.
*
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function makeRemove(child, node) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
content: null,
fromIndex: child._mountIndex,
fromNode: node,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the markup of a node.
*
* @param {string} markup Markup that renders into an element.
* @private
*/
function makeSetMarkup(markup) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.SET_MARKUP,
content: markup,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Make an update for setting the text content.
*
* @param {string} textContent Text content to set.
* @private
*/
function makeTextContent(textContent) {
// NOTE: Null values reduce hidden classes.
return {
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
content: textContent,
fromIndex: null,
fromNode: null,
toIndex: null,
afterNode: null
};
}
/**
* Push an update, if any, onto the queue. Creates a new queue if none is
* passed and always returns the queue. Mutative.
*/
function enqueue(queue, update) {
if (update) {
queue = queue || [];
queue.push(update);
}
return queue;
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue(inst, updateQueue) {
ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue);
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
_reconcilerInstantiateChildren: function (nestedChildren, transaction, context) {
if ("development" !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
} finally {
ReactCurrentOwner.current = null;
}
}
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, removedNodes, transaction, context) {
var nextChildren;
if ("development" !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements);
} finally {
ReactCurrentOwner.current = null;
}
ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context);
return nextChildren;
}
}
nextChildren = flattenChildren(nextNestedChildrenElements);
ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context);
return nextChildren;
},
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function (nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context);
child._mountIndex = index++;
mountImages.push(mountImage);
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function (nextContent) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
!false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : invariant(false) : undefined;
}
}
// Set new text content.
var updates = [makeTextContent(nextContent)];
processQueue(this, updates);
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function (nextMarkup) {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren, false);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
!false ? "development" !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : invariant(false) : undefined;
}
}
var updates = [makeSetMarkup(nextMarkup)];
processQueue(this, updates);
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function (nextNestedChildrenElements, transaction, context) {
// Hook used by React ART
this._updateChildren(nextNestedChildrenElements, transaction, context);
},
/**
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren;
var removedNodes = {};
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, removedNodes, transaction, context);
if (!nextChildren && !prevChildren) {
return;
}
var updates = null;
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
var lastPlacedNode = null;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex));
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
// The `removedNodes` loop below will actually remove the child.
}
// The child must be instantiated before it's mounted.
updates = enqueue(updates, this._mountChildAtIndex(nextChild, lastPlacedNode, nextIndex, transaction, context));
}
nextIndex++;
lastPlacedNode = ReactReconciler.getNativeNode(nextChild);
}
// Remove children that are no longer present.
for (name in removedNodes) {
if (removedNodes.hasOwnProperty(name)) {
updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name]));
}
}
if (updates) {
processQueue(this, updates);
}
this._renderedChildren = nextChildren;
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted. It does not actually perform any
* backend operations.
*
* @internal
*/
unmountChildren: function (safely) {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren, safely);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function (child, afterNode, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
return makeMove(child, afterNode, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function (child, afterNode, mountImage) {
return makeInsertMarkup(mountImage, afterNode, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function (child, node) {
return makeRemove(child, node);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildAtIndex: function (child, afterNode, index, transaction, context) {
var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context);
child._mountIndex = index;
return this.createChild(child, afterNode, mountImage);
},
/**
* Unmounts a rendered child.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @private
*/
_unmountChild: function (child, node) {
var update = this.removeChild(child, node);
child._mountIndex = null;
return update;
}
}
};
module.exports = ReactMultiChild;
},{"132":132,"172":172,"30":30,"35":35,"38":38,"83":83,"93":93}],83:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactMultiChildUpdateTypes
*/
'use strict';
var keyMirror = _dereq_(175);
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
SET_MARKUP: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
},{"175":175}],84:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeComponent
*/
'use strict';
var assign = _dereq_(24);
var invariant = _dereq_(172);
var autoGenerateWrapperClass = null;
var genericComponentClass = null;
// This registry keeps track of wrapper classes around native tags.
var tagToComponentClass = {};
var textComponentClass = null;
var ReactNativeComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function (componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function (componentClass) {
textComponentClass = componentClass;
},
// This accepts a keyed object with classes as values. Each key represents a
// tag. That particular tag will use this class instead of the generic one.
injectComponentClasses: function (componentClasses) {
assign(tagToComponentClass, componentClasses);
}
};
/**
* Get a composite component wrapper class for a specific tag.
*
* @param {ReactElement} element The tag for which to get the class.
* @return {function} The React class constructor function.
*/
function getComponentClassForElement(element) {
if (typeof element.type === 'function') {
return element.type;
}
var tag = element.type;
var componentClass = tagToComponentClass[tag];
if (componentClass == null) {
tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
}
return componentClass;
}
/**
* Get a native internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
!genericComponentClass ? "development" !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined;
return new genericComponentClass(element);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactNativeComponent = {
getComponentClassForElement: getComponentClassForElement,
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactNativeComponentInjection
};
module.exports = ReactNativeComponent;
},{"172":172,"24":24}],85:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNodeTypes
*/
'use strict';
var ReactElement = _dereq_(65);
var invariant = _dereq_(172);
var ReactNodeTypes = {
NATIVE: 0,
COMPOSITE: 1,
EMPTY: 2,
getType: function (node) {
if (node === null || node === false) {
return ReactNodeTypes.EMPTY;
} else if (ReactElement.isValidElement(node)) {
if (typeof node.type === 'function') {
return ReactNodeTypes.COMPOSITE;
} else {
return ReactNodeTypes.NATIVE;
}
}
!false ? "development" !== 'production' ? invariant(false, 'Unexpected node: %s', node) : invariant(false) : undefined;
}
};
module.exports = ReactNodeTypes;
},{"172":172,"65":65}],86:[function(_dereq_,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNoopUpdateQueue
*/
'use strict';
var warning = _dereq_(182);
function warnTDZ(publicInstance, callerName) {
if ("development" !== 'production') {
"development" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
warnTDZ(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
warnTDZ(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
warnTDZ(publicInstance, 'setState');
}
};
module.exports = ReactNoopUpdateQueue;
},{"182":182}],87:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactOwner
*/
'use strict';
var invariant = _dereq_(172);
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function (object) {
return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? "development" !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
var ownerPublicInstance = owner.getPublicInstance();
// Check that `component`'s owner is still alive and that `component` is still the current ref
// because we do not want to detach the ref if another component stole it.
if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
},{"172":172}],88:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPerf
*/
'use strict';
/**
* ReactPerf is a general AOP system designed to measure performance. This
* module only has the hooks: see ReactDefaultPerf for the analysis tool.
*/
var ReactPerf = {
/**
* Boolean to enable/disable measurement. Set to false by default to prevent
* accidental logging and perf loss.
*/
enableMeasure: false,
/**
* Holds onto the measure function in use. By default, don't measure
* anything, but we'll override this if we inject a measure function.
*/
storedMeasure: _noMeasure,
/**
* @param {object} object
* @param {string} objectName
* @param {object<string>} methodNames
*/
measureMethods: function (object, objectName, methodNames) {
if ("development" !== 'production') {
for (var key in methodNames) {
if (!methodNames.hasOwnProperty(key)) {
continue;
}
object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]);
}
}
},
/**
* Use this to wrap methods you want to measure. Zero overhead in production.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function (objName, fnName, func) {
if ("development" !== 'production') {
var measuredFunc = null;
var wrapper = function () {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
wrapper.displayName = objName + '_' + fnName;
return wrapper;
}
return func;
},
injection: {
/**
* @param {function} measure
*/
injectMeasure: function (measure) {
ReactPerf.storedMeasure = measure;
}
}
};
/**
* Simply passes through the measured function, without measuring it.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
function _noMeasure(objName, fnName, func) {
return func;
}
module.exports = ReactPerf;
},{}],89:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocationNames
*/
'use strict';
var ReactPropTypeLocationNames = {};
if ("development" !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],90:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypeLocations
*/
'use strict';
var keyMirror = _dereq_(175);
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
},{"175":175}],91:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactPropTypes
*/
'use strict';
var ReactElement = _dereq_(65);
var ReactPropTypeLocationNames = _dereq_(89);
var emptyFunction = _dereq_(164);
var getIteratorFn = _dereq_(138);
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']');
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOf, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOfType, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
module.exports = ReactPropTypes;
},{"138":138,"164":164,"65":65,"89":89}],92:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconcileTransaction
*/
'use strict';
var CallbackQueue = _dereq_(5);
var PooledClass = _dereq_(25);
var ReactBrowserEventEmitter = _dereq_(27);
var ReactInputSelection = _dereq_(74);
var Transaction = _dereq_(123);
var assign = _dereq_(24);
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function () {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
* restores the previous value.
*/
close: function (previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function () {
this.reactMountReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction(useCreateElement) {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = useCreateElement;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* Save current transaction state -- if the return value from this method is
* passed to `rollback`, the transaction will be reset to that state.
*/
checkpoint: function () {
// reactMountReady is the our only stateful wrapper
return this.reactMountReady.checkpoint();
},
rollback: function (checkpoint) {
this.reactMountReady.rollback(checkpoint);
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"123":123,"24":24,"25":25,"27":27,"5":5,"74":74}],93:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactReconciler
*/
'use strict';
var ReactRef = _dereq_(94);
var ReactInstrumentation = _dereq_(76);
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {?object} the containing native component instance
* @param {?object} info about the native container
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (internalInstance, transaction, nativeParent, nativeContainerInfo, context) {
var markup = internalInstance.mountComponent(transaction, nativeParent, nativeContainerInfo, context);
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onMountComponent(internalInstance);
}
return markup;
},
/**
* Returns a value that can be passed to
* ReactComponentEnvironment.replaceNodeWithMarkup.
*/
getNativeNode: function (internalInstance) {
return internalInstance.getNativeNode();
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (internalInstance, safely) {
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent(safely);
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onUnmountComponent(internalInstance);
}
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function (internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement === prevElement && context === internalInstance._context) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for an element created outside a composite to be
// deeply mutated and reused.
// TODO: Bailing out early is just a perf optimization right?
// TODO: Removing the return statement should affect correctness?
return;
}
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
if (refsChanged) {
ReactRef.detachRefs(internalInstance, prevElement);
}
internalInstance.receiveComponent(nextElement, transaction, context);
if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance);
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (internalInstance, transaction) {
internalInstance.performUpdateIfNecessary(transaction);
if ("development" !== 'production') {
ReactInstrumentation.debugTool.onUpdateComponent(internalInstance);
}
}
};
module.exports = ReactReconciler;
},{"76":76,"94":94}],94:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactRef
*/
'use strict';
var ReactOwner = _dereq_(87);
var ReactRef = {};
function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
}
function detachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(null);
} else {
// Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
}
ReactRef.attachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
attachRef(ref, instance, element._owner);
}
};
ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
return(
// This has a few false positives w/r/t empty components.
prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref
);
};
ReactRef.detachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
detachRef(ref, instance, element._owner);
}
};
module.exports = ReactRef;
},{"87":87}],95:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerBatchingStrategy
*/
'use strict';
var ReactServerBatchingStrategy = {
isBatchingUpdates: false,
batchedUpdates: function (callback) {
// Don't do anything here. During the server rendering we don't want to
// schedule any updates. We will simply ignore them.
}
};
module.exports = ReactServerBatchingStrategy;
},{}],96:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerRendering
*/
'use strict';
var ReactDOMContainerInfo = _dereq_(44);
var ReactDefaultBatchingStrategy = _dereq_(61);
var ReactElement = _dereq_(65);
var ReactMarkupChecksum = _dereq_(80);
var ReactServerBatchingStrategy = _dereq_(95);
var ReactServerRenderingTransaction = _dereq_(97);
var ReactUpdates = _dereq_(104);
var emptyObject = _dereq_(165);
var instantiateReactComponent = _dereq_(143);
var invariant = _dereq_(172);
/**
* @param {ReactElement} element
* @return {string} the HTML markup
*/
function renderToStringImpl(element, makeStaticMarkup) {
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
transaction = ReactServerRenderingTransaction.getPooled(makeStaticMarkup);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element);
var markup = componentInstance.mountComponent(transaction, null, ReactDOMContainerInfo(), emptyObject);
if (!makeStaticMarkup) {
markup = ReactMarkupChecksum.addChecksumToMarkup(markup);
}
return markup;
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
function renderToString(element) {
!ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined;
return renderToStringImpl(element, false);
}
function renderToStaticMarkup(element) {
!ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined;
return renderToStringImpl(element, true);
}
module.exports = {
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup
};
},{"104":104,"143":143,"165":165,"172":172,"44":44,"61":61,"65":65,"80":80,"95":95,"97":97}],97:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerRenderingTransaction
*/
'use strict';
var PooledClass = _dereq_(25);
var Transaction = _dereq_(123);
var assign = _dereq_(24);
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [];
var noopCallbackQueue = {
enqueue: function () {}
};
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.useCreateElement = false;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap procedures.
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return noopCallbackQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {}
};
assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
},{"123":123,"24":24,"25":25}],98:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactStateSetters
*/
'use strict';
var ReactStateSetters = {
/**
* Returns a function that calls the provided function, and uses the result
* of that to set the component's state.
*
* @param {ReactCompositeComponent} component
* @param {function} funcReturningState Returned callback uses this to
* determine how to update state.
* @return {function} callback that when invoked uses funcReturningState to
* determined the object literal to setState.
*/
createStateSetter: function (component, funcReturningState) {
return function (a, b, c, d, e, f) {
var partialState = funcReturningState.call(component, a, b, c, d, e, f);
if (partialState) {
component.setState(partialState);
}
};
},
/**
* Returns a single-argument callback that can be used to update a single
* key in the component's state.
*
* Note: this is memoized function, which makes it inexpensive to call.
*
* @param {ReactCompositeComponent} component
* @param {string} key The key in the state that you should update.
* @return {function} callback of 1 argument which calls setState() with
* the provided keyName and callback argument.
*/
createStateKeySetter: function (component, key) {
// Memoize the setters.
var cache = component.__keySetters || (component.__keySetters = {});
return cache[key] || (cache[key] = createStateKeySetter(component, key));
}
};
function createStateKeySetter(component, key) {
// Partial state is allocated outside of the function closure so it can be
// reused with every call, avoiding memory allocation when this function
// is called.
var partialState = {};
return function stateKeySetter(value) {
partialState[key] = value;
component.setState(partialState);
};
}
ReactStateSetters.Mixin = {
/**
* Returns a function that calls the provided function, and uses the result
* of that to set the component's state.
*
* For example, these statements are equivalent:
*
* this.setState({x: 1});
* this.createStateSetter(function(xValue) {
* return {x: xValue};
* })(1);
*
* @param {function} funcReturningState Returned callback uses this to
* determine how to update state.
* @return {function} callback that when invoked uses funcReturningState to
* determined the object literal to setState.
*/
createStateSetter: function (funcReturningState) {
return ReactStateSetters.createStateSetter(this, funcReturningState);
},
/**
* Returns a single-argument callback that can be used to update a single
* key in the component's state.
*
* For example, these statements are equivalent:
*
* this.setState({x: 1});
* this.createStateKeySetter('x')(1);
*
* Note: this is memoized function, which makes it inexpensive to call.
*
* @param {string} key The key in the state that you should update.
* @return {function} callback of 1 argument which calls setState() with
* the provided keyName and callback argument.
*/
createStateKeySetter: function (key) {
return ReactStateSetters.createStateKeySetter(this, key);
}
};
module.exports = ReactStateSetters;
},{}],99:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTestUtils
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPluginHub = _dereq_(16);
var EventPluginRegistry = _dereq_(17);
var EventPropagators = _dereq_(19);
var React = _dereq_(26);
var ReactDOM = _dereq_(39);
var ReactDOMComponentTree = _dereq_(43);
var ReactElement = _dereq_(65);
var ReactBrowserEventEmitter = _dereq_(27);
var ReactCompositeComponent = _dereq_(37);
var ReactInstanceMap = _dereq_(75);
var ReactUpdates = _dereq_(104);
var SyntheticEvent = _dereq_(114);
var assign = _dereq_(24);
var emptyObject = _dereq_(165);
var findDOMNode = _dereq_(131);
var invariant = _dereq_(172);
var topLevelTypes = EventConstants.topLevelTypes;
function Event(suffix) {}
/**
* @class ReactTestUtils
*/
function findAllInRenderedTreeInternal(inst, test) {
if (!inst || !inst.getPublicInstance) {
return [];
}
var publicInst = inst.getPublicInstance();
var ret = test(publicInst) ? [publicInst] : [];
var currentElement = inst._currentElement;
if (ReactTestUtils.isDOMComponent(publicInst)) {
var renderedChildren = inst._renderedChildren;
var key;
for (key in renderedChildren) {
if (!renderedChildren.hasOwnProperty(key)) {
continue;
}
ret = ret.concat(findAllInRenderedTreeInternal(renderedChildren[key], test));
}
} else if (ReactElement.isValidElement(currentElement) && typeof currentElement.type === 'function') {
ret = ret.concat(findAllInRenderedTreeInternal(inst._renderedComponent, test));
}
return ret;
}
/**
* Todo: Support the entire DOM.scry query syntax. For now, these simple
* utilities will suffice for testing purposes.
* @lends ReactTestUtils
*/
var ReactTestUtils = {
renderIntoDocument: function (instance) {
var div = document.createElement('div');
// None of our tests actually require attaching the container to the
// DOM, and doing so creates a mess that we rely on test isolation to
// clean up, so we're going to stop honoring the name of this method
// (and probably rename it eventually) if no problems arise.
// document.documentElement.appendChild(div);
return ReactDOM.render(instance, div);
},
isElement: function (element) {
return ReactElement.isValidElement(element);
},
isElementOfType: function (inst, convenienceConstructor) {
return ReactElement.isValidElement(inst) && inst.type === convenienceConstructor;
},
isDOMComponent: function (inst) {
return !!(inst && inst.nodeType === 1 && inst.tagName);
},
isDOMComponentElement: function (inst) {
return !!(inst && ReactElement.isValidElement(inst) && !!inst.tagName);
},
isCompositeComponent: function (inst) {
if (ReactTestUtils.isDOMComponent(inst)) {
// Accessing inst.setState warns; just return false as that'll be what
// this returns when we have DOM nodes as refs directly
return false;
}
return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
},
isCompositeComponentWithType: function (inst, type) {
if (!ReactTestUtils.isCompositeComponent(inst)) {
return false;
}
var internalInstance = ReactInstanceMap.get(inst);
var constructor = internalInstance._currentElement.type;
return constructor === type;
},
isCompositeComponentElement: function (inst) {
if (!ReactElement.isValidElement(inst)) {
return false;
}
// We check the prototype of the type that will get mounted, not the
// instance itself. This is a future proof way of duck typing.
var prototype = inst.type.prototype;
return typeof prototype.render === 'function' && typeof prototype.setState === 'function';
},
isCompositeComponentElementWithType: function (inst, type) {
var internalInstance = ReactInstanceMap.get(inst);
var constructor = internalInstance._currentElement.type;
return !!(ReactTestUtils.isCompositeComponentElement(inst) && constructor === type);
},
getRenderedChildOfCompositeComponent: function (inst) {
if (!ReactTestUtils.isCompositeComponent(inst)) {
return null;
}
var internalInstance = ReactInstanceMap.get(inst);
return internalInstance._renderedComponent.getPublicInstance();
},
findAllInRenderedTree: function (inst, test) {
if (!inst) {
return [];
}
!ReactTestUtils.isCompositeComponent(inst) ? "development" !== 'production' ? invariant(false, 'findAllInRenderedTree(...): instance must be a composite component') : invariant(false) : undefined;
return findAllInRenderedTreeInternal(ReactInstanceMap.get(inst), test);
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the class name matching `className`.
* @return {array} an array of all the matches.
*/
scryRenderedDOMComponentsWithClass: function (root, classNames) {
if (!Array.isArray(classNames)) {
classNames = classNames.split(/\s+/);
}
return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
if (ReactTestUtils.isDOMComponent(inst)) {
var className = inst.className;
if (typeof className !== 'string') {
// SVG, probably.
className = inst.getAttribute('class') || '';
}
var classList = className.split(/\s+/);
return classNames.every(function (name) {
return classList.indexOf(name) !== -1;
});
}
return false;
});
},
/**
* Like scryRenderedDOMComponentsWithClass but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithClass: function (root, className) {
var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className);
if (all.length !== 1) {
throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
}
return all[0];
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the tag name matching `tagName`.
* @return {array} an array of all the matches.
*/
scryRenderedDOMComponentsWithTag: function (root, tagName) {
return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
});
},
/**
* Like scryRenderedDOMComponentsWithTag but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithTag: function (root, tagName) {
var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName);
if (all.length !== 1) {
throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
}
return all[0];
},
/**
* Finds all instances of components with type equal to `componentType`.
* @return {array} an array of all the matches.
*/
scryRenderedComponentsWithType: function (root, componentType) {
return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
return ReactTestUtils.isCompositeComponentWithType(inst, componentType);
});
},
/**
* Same as `scryRenderedComponentsWithType` but expects there to be one result
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactComponent} The one match.
*/
findRenderedComponentWithType: function (root, componentType) {
var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType);
if (all.length !== 1) {
throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
}
return all[0];
},
/**
* Pass a mocked component module to this method to augment it with
* useful methods that allow it to be used as a dummy React component.
* Instead of rendering as usual, the component will become a simple
* <div> containing any provided children.
*
* @param {object} module the mock function object exported from a
* module that defines the component to be mocked
* @param {?string} mockTagName optional dummy root tag name to return
* from render method (overrides
* module.mockTagName if provided)
* @return {object} the ReactTestUtils object (for chaining)
*/
mockComponent: function (module, mockTagName) {
mockTagName = mockTagName || module.mockTagName || 'div';
module.prototype.render.mockImplementation(function () {
return React.createElement(mockTagName, null, this.props.children);
});
return this;
},
/**
* Simulates a top level event being dispatched from a raw event that occurred
* on an `Element` node.
* @param {Object} topLevelType A type from `EventConstants.topLevelTypes`
* @param {!Element} node The dom to simulate an event occurring on.
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnNode: function (topLevelType, node, fakeNativeEvent) {
fakeNativeEvent.target = node;
ReactBrowserEventEmitter.ReactEventListener.dispatchEvent(topLevelType, fakeNativeEvent);
},
/**
* Simulates a top level event being dispatched from a raw event that occurred
* on the `ReactDOMComponent` `comp`.
* @param {Object} topLevelType A type from `EventConstants.topLevelTypes`.
* @param {!ReactDOMComponent} comp
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnDOMComponent: function (topLevelType, comp, fakeNativeEvent) {
ReactTestUtils.simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent);
},
nativeTouchData: function (x, y) {
return {
touches: [{ pageX: x, pageY: y }]
};
},
createRenderer: function () {
return new ReactShallowRenderer();
},
Simulate: null,
SimulateNative: {}
};
/**
* @class ReactShallowRenderer
*/
var ReactShallowRenderer = function () {
this._instance = null;
};
ReactShallowRenderer.prototype.getMountedInstance = function () {
return this._instance ? this._instance._instance : null;
};
var NoopInternalComponent = function (element) {
this._renderedOutput = element;
this._currentElement = element;
};
NoopInternalComponent.prototype = {
mountComponent: function () {},
receiveComponent: function (element) {
this._renderedOutput = element;
this._currentElement = element;
},
getNativeNode: function () {
return undefined;
},
unmountComponent: function () {},
getPublicInstance: function () {
return null;
}
};
var ShallowComponentWrapper = function (element) {
this.construct(element);
};
assign(ShallowComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
_instantiateReactComponent: function (element) {
return new NoopInternalComponent(element);
},
_replaceNodeWithMarkup: function () {},
_renderValidatedComponent: ReactCompositeComponent.Mixin._renderValidatedComponentWithoutOwnerOrContext
});
ReactShallowRenderer.prototype.render = function (element, context) {
!ReactElement.isValidElement(element) ? "development" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Invalid component element.%s', typeof element === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : '') : invariant(false) : undefined;
!(typeof element.type !== 'string') ? "development" !== 'production' ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom ' + 'components, not primitives (%s). Instead of calling `.render(el)` and ' + 'inspecting the rendered output, look at `el.props` directly instead.', element.type) : invariant(false) : undefined;
if (!context) {
context = emptyObject;
}
ReactUpdates.batchedUpdates(_batchedRender, this, element, context);
return this.getRenderOutput();
};
function _batchedRender(renderer, element, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(true);
renderer._render(element, transaction, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
ReactShallowRenderer.prototype.getRenderOutput = function () {
return this._instance && this._instance._renderedComponent && this._instance._renderedComponent._renderedOutput || null;
};
ReactShallowRenderer.prototype.unmount = function () {
if (this._instance) {
this._instance.unmountComponent(false);
}
};
ReactShallowRenderer.prototype._render = function (element, transaction, context) {
if (this._instance) {
this._instance.receiveComponent(element, transaction, context);
} else {
var instance = new ShallowComponentWrapper(element);
instance.mountComponent(transaction, null, null, context);
this._instance = instance;
}
};
/**
* Exports:
*
* - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)`
* - `ReactTestUtils.Simulate.mouseMove(Element/ReactDOMComponent)`
* - `ReactTestUtils.Simulate.change(Element/ReactDOMComponent)`
* - ... (All keys from event plugin `eventTypes` objects)
*/
function makeSimulator(eventType) {
return function (domComponentOrNode, eventData) {
var node;
!!React.isValidElement(domComponentOrNode) ? "development" !== 'production' ? invariant(false, 'TestUtils.Simulate expects a component instance and not a ReactElement.' + 'TestUtils.Simulate will not work if you are using shallow rendering.') : invariant(false) : undefined;
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
node = findDOMNode(domComponentOrNode);
} else if (domComponentOrNode.tagName) {
node = domComponentOrNode;
}
var dispatchConfig = EventPluginRegistry.eventNameDispatchConfigs[eventType];
var fakeNativeEvent = new Event();
fakeNativeEvent.target = node;
// We don't use SyntheticEvent.getPooled in order to not have to worry about
// properly destroying any properties assigned from `eventData` upon release
var event = new SyntheticEvent(dispatchConfig, ReactDOMComponentTree.getInstanceFromNode(node), fakeNativeEvent, node);
assign(event, eventData);
if (dispatchConfig.phasedRegistrationNames) {
EventPropagators.accumulateTwoPhaseDispatches(event);
} else {
EventPropagators.accumulateDirectDispatches(event);
}
ReactUpdates.batchedUpdates(function () {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue(true);
});
};
}
function buildSimulators() {
ReactTestUtils.Simulate = {};
var eventType;
for (eventType in EventPluginRegistry.eventNameDispatchConfigs) {
/**
* @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?object} eventData Fake event data to use in SyntheticEvent.
*/
ReactTestUtils.Simulate[eventType] = makeSimulator(eventType);
}
}
// Rebuild ReactTestUtils.Simulate whenever event plugins are injected
var oldInjectEventPluginOrder = EventPluginHub.injection.injectEventPluginOrder;
EventPluginHub.injection.injectEventPluginOrder = function () {
oldInjectEventPluginOrder.apply(this, arguments);
buildSimulators();
};
var oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName;
EventPluginHub.injection.injectEventPluginsByName = function () {
oldInjectEventPlugins.apply(this, arguments);
buildSimulators();
};
buildSimulators();
/**
* Exports:
*
* - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)`
* - ... (All keys from `EventConstants.topLevelTypes`)
*
* Note: Top level event types are a subset of the entire set of handler types
* (which include a broader set of "synthetic" events). For example, onDragDone
* is a synthetic event. Except when testing an event plugin or React's event
* handling code specifically, you probably want to use ReactTestUtils.Simulate
* to dispatch synthetic events.
*/
function makeNativeSimulator(eventType) {
return function (domComponentOrNode, nativeEventData) {
var fakeNativeEvent = new Event(eventType);
assign(fakeNativeEvent, nativeEventData);
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
ReactTestUtils.simulateNativeEventOnDOMComponent(eventType, domComponentOrNode, fakeNativeEvent);
} else if (domComponentOrNode.tagName) {
// Will allow on actual dom nodes.
ReactTestUtils.simulateNativeEventOnNode(eventType, domComponentOrNode, fakeNativeEvent);
}
};
}
Object.keys(topLevelTypes).forEach(function (eventType) {
// Event type is stored as 'topClick' - we transform that to 'click'
var convenienceName = eventType.indexOf('top') === 0 ? eventType.charAt(3).toLowerCase() + eventType.substr(4) : eventType;
/**
* @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
*/
ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(eventType);
});
module.exports = ReactTestUtils;
},{"104":104,"114":114,"131":131,"15":15,"16":16,"165":165,"17":17,"172":172,"19":19,"24":24,"26":26,"27":27,"37":37,"39":39,"43":43,"65":65,"75":75}],100:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTransitionChildMapping
*/
'use strict';
var flattenChildren = _dereq_(132);
var ReactTransitionChildMapping = {
/**
* Given `this.props.children`, return an object mapping key to child. Just
* simple syntactic sugar around flattenChildren().
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
getChildMapping: function (children) {
if (!children) {
return children;
}
return flattenChildren(children);
},
/**
* When you're adding or removing children some may be added or removed in the
* same render pass. We want to show *both* since we want to simultaneously
* animate elements in and out. This function takes a previous set of keys
* and a new set of keys and merges them with its best guess of the correct
* ordering. In the future we may expose some of the utilities in
* ReactMultiChild to make this easy, but for now React itself does not
* directly have this concept of the union of prevChildren and nextChildren
* so we implement it here.
*
* @param {object} prev prev children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @param {object} next next children as returned from
* `ReactTransitionChildMapping.getChildMapping()`.
* @return {object} a key set that contains all keys in `prev` and all keys
* in `next` in a reasonable order.
*/
mergeChildMappings: function (prev, next) {
prev = prev || {};
next = next || {};
function getValueForKey(key) {
if (next.hasOwnProperty(key)) {
return next[key];
} else {
return prev[key];
}
}
// For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextKeysPending = {};
var pendingKeys = [];
for (var prevKey in prev) {
if (next.hasOwnProperty(prevKey)) {
if (pendingKeys.length) {
nextKeysPending[prevKey] = pendingKeys;
pendingKeys = [];
}
} else {
pendingKeys.push(prevKey);
}
}
var i;
var childMapping = {};
for (var nextKey in next) {
if (nextKeysPending.hasOwnProperty(nextKey)) {
for (i = 0; i < nextKeysPending[nextKey].length; i++) {
var pendingNextKey = nextKeysPending[nextKey][i];
childMapping[nextKeysPending[nextKey][i]] = getValueForKey(pendingNextKey);
}
}
childMapping[nextKey] = getValueForKey(nextKey);
}
// Finally, add the keys which didn't appear before any key in `next`
for (i = 0; i < pendingKeys.length; i++) {
childMapping[pendingKeys[i]] = getValueForKey(pendingKeys[i]);
}
return childMapping;
}
};
module.exports = ReactTransitionChildMapping;
},{"132":132}],101:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTransitionEvents
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
var getVendorPrefixedEventName = _dereq_(142);
var endEvents = [];
function detectEvents() {
var animEnd = getVendorPrefixedEventName('animationend');
var transEnd = getVendorPrefixedEventName('transitionend');
if (animEnd) {
endEvents.push(animEnd);
}
if (transEnd) {
endEvents.push(transEnd);
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
},{"142":142,"158":158}],102:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTransitionGroup
*/
'use strict';
var React = _dereq_(26);
var ReactTransitionChildMapping = _dereq_(100);
var assign = _dereq_(24);
var emptyFunction = _dereq_(164);
var ReactTransitionGroup = React.createClass({
displayName: 'ReactTransitionGroup',
propTypes: {
component: React.PropTypes.any,
childFactory: React.PropTypes.func
},
getDefaultProps: function () {
return {
component: 'span',
childFactory: emptyFunction.thatReturnsArgument
};
},
getInitialState: function () {
return {
children: ReactTransitionChildMapping.getChildMapping(this.props.children)
};
},
componentWillMount: function () {
this.currentlyTransitioningKeys = {};
this.keysToEnter = [];
this.keysToLeave = [];
},
componentDidMount: function () {
var initialChildMapping = this.state.children;
for (var key in initialChildMapping) {
if (initialChildMapping[key]) {
this.performAppear(key);
}
}
},
componentWillReceiveProps: function (nextProps) {
var nextChildMapping = ReactTransitionChildMapping.getChildMapping(nextProps.children);
var prevChildMapping = this.state.children;
this.setState({
children: ReactTransitionChildMapping.mergeChildMappings(prevChildMapping, nextChildMapping)
});
var key;
for (key in nextChildMapping) {
var hasPrev = prevChildMapping && prevChildMapping.hasOwnProperty(key);
if (nextChildMapping[key] && !hasPrev && !this.currentlyTransitioningKeys[key]) {
this.keysToEnter.push(key);
}
}
for (key in prevChildMapping) {
var hasNext = nextChildMapping && nextChildMapping.hasOwnProperty(key);
if (prevChildMapping[key] && !hasNext && !this.currentlyTransitioningKeys[key]) {
this.keysToLeave.push(key);
}
}
// If we want to someday check for reordering, we could do it here.
},
componentDidUpdate: function () {
var keysToEnter = this.keysToEnter;
this.keysToEnter = [];
keysToEnter.forEach(this.performEnter);
var keysToLeave = this.keysToLeave;
this.keysToLeave = [];
keysToLeave.forEach(this.performLeave);
},
performAppear: function (key) {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillAppear) {
component.componentWillAppear(this._handleDoneAppearing.bind(this, key));
} else {
this._handleDoneAppearing(key);
}
},
_handleDoneAppearing: function (key) {
var component = this.refs[key];
if (component.componentDidAppear) {
component.componentDidAppear();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children);
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
// This was removed before it had fully appeared. Remove it.
this.performLeave(key);
}
},
performEnter: function (key) {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillEnter) {
component.componentWillEnter(this._handleDoneEntering.bind(this, key));
} else {
this._handleDoneEntering(key);
}
},
_handleDoneEntering: function (key) {
var component = this.refs[key];
if (component.componentDidEnter) {
component.componentDidEnter();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children);
if (!currentChildMapping || !currentChildMapping.hasOwnProperty(key)) {
// This was removed before it had fully entered. Remove it.
this.performLeave(key);
}
},
performLeave: function (key) {
this.currentlyTransitioningKeys[key] = true;
var component = this.refs[key];
if (component.componentWillLeave) {
component.componentWillLeave(this._handleDoneLeaving.bind(this, key));
} else {
// Note that this is somewhat dangerous b/c it calls setState()
// again, effectively mutating the component before all the work
// is done.
this._handleDoneLeaving(key);
}
},
_handleDoneLeaving: function (key) {
var component = this.refs[key];
if (component.componentDidLeave) {
component.componentDidLeave();
}
delete this.currentlyTransitioningKeys[key];
var currentChildMapping = ReactTransitionChildMapping.getChildMapping(this.props.children);
if (currentChildMapping && currentChildMapping.hasOwnProperty(key)) {
// This entered again before it fully left. Add it again.
this.performEnter(key);
} else {
this.setState(function (state) {
var newChildren = assign({}, state.children);
delete newChildren[key];
return { children: newChildren };
});
}
},
render: function () {
// TODO: we could get rid of the need for the wrapper node
// by cloning a single child
var childrenToRender = [];
for (var key in this.state.children) {
var child = this.state.children[key];
if (child) {
// You may need to apply reactive updates to a child as it is leaving.
// The normal React way to do it won't work since the child will have
// already been removed. In case you need this behavior you can provide
// a childFactory function to wrap every child, even the ones that are
// leaving.
childrenToRender.push(React.cloneElement(this.props.childFactory(child), { ref: key, key: key }));
}
}
return React.createElement(this.props.component, this.props, childrenToRender);
}
});
module.exports = ReactTransitionGroup;
},{"100":100,"164":164,"24":24,"26":26}],103:[function(_dereq_,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdateQueue
*/
'use strict';
var ReactCurrentOwner = _dereq_(38);
var ReactInstanceMap = _dereq_(75);
var ReactUpdates = _dereq_(104);
var invariant = _dereq_(172);
var warning = _dereq_(182);
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if ("development" !== 'production') {
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
"development" !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined;
}
return null;
}
if ("development" !== 'production') {
"development" !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : undefined;
}
return internalInstance;
}
/**
* ReactUpdateQueue allows for state updates to be scheduled into a later
* reconciliation step.
*/
var ReactUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
if ("development" !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
"development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(publicInstance);
if (internalInstance) {
// During componentWillMount and render this will still be null but after
// that will always render to something. At least for now. So we can use
// this hack.
return !!internalInstance._renderedComponent;
} else {
return false;
}
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {
!(typeof callback === 'function') ? "development" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback of type ' + '%s. A function is expected', typeof callback === 'object' && Object.keys(callback).length && Object.keys(callback).length < 20 ? typeof callback + ' (keys: ' + Object.keys(callback) + ')' : typeof callback) : invariant(false) : undefined;
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function (internalInstance, callback) {
!(typeof callback === 'function') ? "development" !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback of type ' + '%s. A function is expected', typeof callback === 'object' && Object.keys(callback).length && Object.keys(callback).length < 20 ? typeof callback + ' (keys: ' + Object.keys(callback) + ')' : typeof callback) : invariant(false) : undefined;
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
if (!internalInstance) {
return;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
if (!internalInstance) {
return;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
enqueueElementInternal: function (internalInstance, newElement) {
internalInstance._pendingElement = newElement;
enqueueUpdate(internalInstance);
}
};
module.exports = ReactUpdateQueue;
},{"104":104,"172":172,"182":182,"38":38,"75":75}],104:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdates
*/
'use strict';
var CallbackQueue = _dereq_(5);
var PooledClass = _dereq_(25);
var ReactFeatureFlags = _dereq_(71);
var ReactPerf = _dereq_(88);
var ReactReconciler = _dereq_(93);
var Transaction = _dereq_(123);
var assign = _dereq_(24);
var invariant = _dereq_(172);
var dirtyComponents = [];
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
!(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined;
}
var NESTED_UPDATES = {
initialize: function () {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function () {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function () {
this.callbackQueue.reset();
},
close: function () {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled();
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* useCreateElement */true);
}
assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
destructor: function () {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function (method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
!(len === dirtyComponents.length) ? "development" !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined;
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i];
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
var markerName;
if (ReactFeatureFlags.logTopLevelRenders) {
var namedComponent = component;
// Duck type TopLevelWrapper. This is probably always true.
if (component._currentElement.props === component._renderedComponent._currentElement) {
namedComponent = component._renderedComponent;
}
markerName = 'React update: ' + namedComponent.getName();
console.time(markerName);
}
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction);
if (markerName) {
console.timeEnd(markerName);
}
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
}
}
}
}
var flushBatchedUpdates = function () {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = false;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled();
queue.notifyAll();
CallbackQueue.release(queue);
}
}
};
flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates);
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
!batchingStrategy.isBatchingUpdates ? "development" !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined;
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function (ReconcileTransaction) {
!ReconcileTransaction ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined;
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function (_batchingStrategy) {
!_batchingStrategy ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined;
!(typeof _batchingStrategy.batchedUpdates === 'function') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined;
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? "development" !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined;
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
},{"123":123,"172":172,"24":24,"25":25,"5":5,"71":71,"88":88,"93":93}],105:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactVersion
*/
'use strict';
module.exports = '15.0.0-rc.2';
},{}],106:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactWithAddons
*/
/**
* This module exists purely in the open source project, and is meant as a way
* to create a separate standalone build of React. This build has "addons", or
* functionality we've built and think might be useful but doesn't have a good
* place to live inside React core.
*/
'use strict';
var LinkedStateMixin = _dereq_(22);
var React = _dereq_(26);
var ReactComponentWithPureRenderMixin = _dereq_(36);
var ReactCSSTransitionGroup = _dereq_(28);
var ReactFragment = _dereq_(72);
var ReactTransitionGroup = _dereq_(102);
var shallowCompare = _dereq_(151);
var update = _dereq_(154);
React.addons = {
CSSTransitionGroup: ReactCSSTransitionGroup,
LinkedStateMixin: LinkedStateMixin,
PureRenderMixin: ReactComponentWithPureRenderMixin,
TransitionGroup: ReactTransitionGroup,
createFragment: ReactFragment.create,
shallowCompare: shallowCompare,
update: update
};
if ("development" !== 'production') {
React.addons.Perf = _dereq_(63);
React.addons.TestUtils = _dereq_(99);
}
module.exports = React;
},{"102":102,"151":151,"154":154,"22":22,"26":26,"28":28,"36":36,"63":63,"72":72,"99":99}],107:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SVGDOMPropertyConfig
*/
'use strict';
var NS = {
xlink: 'http://www.w3.org/1999/xlink',
xml: 'http://www.w3.org/XML/1998/namespace'
};
// We use attributes for everything SVG so let's avoid some duplication and run
// code instead.
// The following are all specified in the HTML config already so we exclude here.
// - class (as className)
// - color
// - height
// - id
// - lang
// - max
// - media
// - method
// - min
// - name
// - style
// - target
// - type
// - width
var ATTRS = {
accentHeight: 'accent-height',
accumulate: 0,
additive: 0,
alignmentBaseline: 'alignment-baseline',
allowReorder: 'allowReorder',
alphabetic: 0,
amplitude: 0,
arabicForm: 'arabic-form',
ascent: 0,
attributeName: 'attributeName',
attributeType: 'attributeType',
autoReverse: 'autoReverse',
azimuth: 0,
baseFrequency: 'baseFrequency',
baseProfile: 'baseProfile',
baselineShift: 'baseline-shift',
bbox: 0,
begin: 0,
bias: 0,
by: 0,
calcMode: 'calcMode',
capHeight: 'cap-height',
clip: 0,
clipPath: 'clip-path',
clipRule: 'clip-rule',
clipPathUnits: 'clipPathUnits',
colorInterpolation: 'color-interpolation',
colorInterpolationFilters: 'color-interpolation-filters',
colorProfile: 'color-profile',
colorRendering: 'color-rendering',
contentScriptType: 'contentScriptType',
contentStyleType: 'contentStyleType',
cursor: 0,
cx: 0,
cy: 0,
d: 0,
decelerate: 0,
descent: 0,
diffuseConstant: 'diffuseConstant',
direction: 0,
display: 0,
divisor: 0,
dominantBaseline: 'dominant-baseline',
dur: 0,
dx: 0,
dy: 0,
edgeMode: 'edgeMode',
elevation: 0,
enableBackground: 'enable-background',
end: 0,
exponent: 0,
externalResourcesRequired: 'externalResourcesRequired',
fill: 0,
fillOpacity: 'fill-opacity',
fillRule: 'fill-rule',
filter: 0,
filterRes: 'filterRes',
filterUnits: 'filterUnits',
floodColor: 'flood-color',
floodOpacity: 'flood-opacity',
focusable: 0,
fontFamily: 'font-family',
fontSize: 'font-size',
fontSizeAdjust: 'font-size-adjust',
fontStretch: 'font-stretch',
fontStyle: 'font-style',
fontVariant: 'font-variant',
fontWeight: 'font-weight',
format: 0,
from: 0,
fx: 0,
fy: 0,
g1: 0,
g2: 0,
glyphName: 'glyph-name',
glyphOrientationHorizontal: 'glyph-orientation-horizontal',
glyphOrientationVertical: 'glyph-orientation-vertical',
glyphRef: 'glyphRef',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
hanging: 0,
horizAdvX: 'horiz-adv-x',
horizOriginX: 'horiz-origin-x',
ideographic: 0,
imageRendering: 'image-rendering',
'in': 0,
in2: 0,
intercept: 0,
k: 0,
k1: 0,
k2: 0,
k3: 0,
k4: 0,
kernelMatrix: 'kernelMatrix',
kernelUnitLength: 'kernelUnitLength',
kerning: 0,
keyPoints: 'keyPoints',
keySplines: 'keySplines',
keyTimes: 'keyTimes',
lengthAdjust: 'lengthAdjust',
letterSpacing: 'letter-spacing',
lightingColor: 'lighting-color',
limitingConeAngle: 'limitingConeAngle',
local: 0,
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
markerHeight: 'markerHeight',
markerUnits: 'markerUnits',
markerWidth: 'markerWidth',
mask: 0,
maskContentUnits: 'maskContentUnits',
maskUnits: 'maskUnits',
mathematical: 0,
mode: 0,
numOctaves: 'numOctaves',
offset: 0,
opacity: 0,
operator: 0,
order: 0,
orient: 0,
orientation: 0,
origin: 0,
overflow: 0,
overlinePosition: 'overline-position',
overlineThickness: 'overline-thickness',
paintOrder: 'paint-order',
panose1: 'panose-1',
pathLength: 'pathLength',
patternContentUnits: 'patternContentUnits',
patternTransform: 'patternTransform',
patternUnits: 'patternUnits',
pointerEvents: 'pointer-events',
points: 0,
pointsAtX: 'pointsAtX',
pointsAtY: 'pointsAtY',
pointsAtZ: 'pointsAtZ',
preserveAlpha: 'preserveAlpha',
preserveAspectRatio: 'preserveAspectRatio',
primitiveUnits: 'primitiveUnits',
r: 0,
radius: 0,
refX: 'refX',
refY: 'refY',
renderingIntent: 'rendering-intent',
repeatCount: 'repeatCount',
repeatDur: 'repeatDur',
requiredExtensions: 'requiredExtensions',
requiredFeatures: 'requiredFeatures',
restart: 0,
result: 0,
rotate: 0,
rx: 0,
ry: 0,
scale: 0,
seed: 0,
shapeRendering: 'shape-rendering',
slope: 0,
spacing: 0,
specularConstant: 'specularConstant',
specularExponent: 'specularExponent',
speed: 0,
spreadMethod: 'spreadMethod',
startOffset: 'startOffset',
stdDeviation: 'stdDeviation',
stemh: 0,
stemv: 0,
stitchTiles: 'stitchTiles',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strikethroughPosition: 'strikethrough-position',
strikethroughThickness: 'strikethrough-thickness',
string: 0,
stroke: 0,
strokeDasharray: 'stroke-dasharray',
strokeDashoffset: 'stroke-dashoffset',
strokeLinecap: 'stroke-linecap',
strokeLinejoin: 'stroke-linejoin',
strokeMiterlimit: 'stroke-miterlimit',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
surfaceScale: 'surfaceScale',
systemLanguage: 'systemLanguage',
tableValues: 'tableValues',
targetX: 'targetX',
targetY: 'targetY',
textAnchor: 'text-anchor',
textDecoration: 'text-decoration',
textRendering: 'text-rendering',
textLength: 'textLength',
to: 0,
transform: 0,
u1: 0,
u2: 0,
underlinePosition: 'underline-position',
underlineThickness: 'underline-thickness',
unicode: 0,
unicodeBidi: 'unicode-bidi',
unicodeRange: 'unicode-range',
unitsPerEm: 'units-per-em',
vAlphabetic: 'v-alphabetic',
vHanging: 'v-hanging',
vIdeographic: 'v-ideographic',
vMathematical: 'v-mathematical',
values: 0,
vectorEffect: 'vector-effect',
version: 0,
vertAdvY: 'vert-adv-y',
vertOriginX: 'vert-origin-x',
vertOriginY: 'vert-origin-y',
viewBox: 'viewBox',
viewTarget: 'viewTarget',
visibility: 0,
widths: 0,
wordSpacing: 'word-spacing',
writingMode: 'writing-mode',
x: 0,
xHeight: 'x-height',
x1: 0,
x2: 0,
xChannelSelector: 'xChannelSelector',
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',
y: 0,
y1: 0,
y2: 0,
yChannelSelector: 'yChannelSelector',
z: 0,
zoomAndPan: 'zoomAndPan'
};
var SVGDOMPropertyConfig = {
Properties: {},
DOMAttributeNamespaces: {
xlinkActuate: NS.xlink,
xlinkArcrole: NS.xlink,
xlinkHref: NS.xlink,
xlinkRole: NS.xlink,
xlinkShow: NS.xlink,
xlinkTitle: NS.xlink,
xlinkType: NS.xlink,
xmlBase: NS.xml,
xmlLang: NS.xml,
xmlSpace: NS.xml
},
DOMAttributeNames: {}
};
Object.keys(ATTRS).map(function (key) {
SVGDOMPropertyConfig.Properties[key] = 0;
if (ATTRS[key]) {
SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key];
}
});
module.exports = SVGDOMPropertyConfig;
},{}],108:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SelectEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventPropagators = _dereq_(19);
var ExecutionEnvironment = _dereq_(158);
var ReactDOMComponentTree = _dereq_(43);
var ReactInputSelection = _dereq_(74);
var SyntheticEvent = _dereq_(114);
var getActiveElement = _dereq_(167);
var isTextInputElement = _dereq_(145);
var keyOf = _dereq_(176);
var shallowEqual = _dereq_(181);
var topLevelTypes = EventConstants.topLevelTypes;
var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({ onSelect: null }),
captured: keyOf({ onSelectCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange]
}
};
var activeElement = null;
var activeElementInst = null;
var lastSelection = null;
var mouseDown = false;
// Track whether a listener exists for this plugin. If none exist, we do
// not extract events. See #3639.
var hasListener = false;
var ON_SELECT_KEY = keyOf({ onSelect: null });
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @return {object}
*/
function getSelection(node) {
if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown || activeElement == null || activeElement !== getActiveElement()) {
return null;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
return null;
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
if (!hasListener) {
return null;
}
var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window;
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
activeElement = targetNode;
activeElementInst = targetInst;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementInst = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent, nativeEventTarget);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case topLevelTypes.topSelectionChange:
if (skipSelectionChangeEvent) {
break;
}
// falls through
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent, nativeEventTarget);
}
return null;
},
didPutListener: function (inst, registrationName, listener) {
if (registrationName === ON_SELECT_KEY) {
hasListener = true;
}
}
};
module.exports = SelectEventPlugin;
},{"114":114,"145":145,"15":15,"158":158,"167":167,"176":176,"181":181,"19":19,"43":43,"74":74}],109:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SimpleEventPlugin
*/
'use strict';
var EventConstants = _dereq_(15);
var EventListener = _dereq_(157);
var EventPropagators = _dereq_(19);
var ReactDOMComponentTree = _dereq_(43);
var SyntheticAnimationEvent = _dereq_(110);
var SyntheticClipboardEvent = _dereq_(111);
var SyntheticEvent = _dereq_(114);
var SyntheticFocusEvent = _dereq_(115);
var SyntheticKeyboardEvent = _dereq_(117);
var SyntheticMouseEvent = _dereq_(118);
var SyntheticDragEvent = _dereq_(113);
var SyntheticTouchEvent = _dereq_(119);
var SyntheticTransitionEvent = _dereq_(120);
var SyntheticUIEvent = _dereq_(121);
var SyntheticWheelEvent = _dereq_(122);
var emptyFunction = _dereq_(164);
var getEventCharCode = _dereq_(134);
var invariant = _dereq_(172);
var keyOf = _dereq_(176);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
abort: {
phasedRegistrationNames: {
bubbled: keyOf({ onAbort: true }),
captured: keyOf({ onAbortCapture: true })
}
},
animationEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationEnd: true }),
captured: keyOf({ onAnimationEndCapture: true })
}
},
animationIteration: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationIteration: true }),
captured: keyOf({ onAnimationIterationCapture: true })
}
},
animationStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onAnimationStart: true }),
captured: keyOf({ onAnimationStartCapture: true })
}
},
blur: {
phasedRegistrationNames: {
bubbled: keyOf({ onBlur: true }),
captured: keyOf({ onBlurCapture: true })
}
},
canPlay: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlay: true }),
captured: keyOf({ onCanPlayCapture: true })
}
},
canPlayThrough: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlayThrough: true }),
captured: keyOf({ onCanPlayThroughCapture: true })
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({ onClick: true }),
captured: keyOf({ onClickCapture: true })
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({ onContextMenu: true }),
captured: keyOf({ onContextMenuCapture: true })
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({ onCopy: true }),
captured: keyOf({ onCopyCapture: true })
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({ onCut: true }),
captured: keyOf({ onCutCapture: true })
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({ onDoubleClick: true }),
captured: keyOf({ onDoubleClickCapture: true })
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrag: true }),
captured: keyOf({ onDragCapture: true })
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnd: true }),
captured: keyOf({ onDragEndCapture: true })
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnter: true }),
captured: keyOf({ onDragEnterCapture: true })
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragExit: true }),
captured: keyOf({ onDragExitCapture: true })
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragLeave: true }),
captured: keyOf({ onDragLeaveCapture: true })
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragOver: true }),
captured: keyOf({ onDragOverCapture: true })
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragStart: true }),
captured: keyOf({ onDragStartCapture: true })
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrop: true }),
captured: keyOf({ onDropCapture: true })
}
},
durationChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onDurationChange: true }),
captured: keyOf({ onDurationChangeCapture: true })
}
},
emptied: {
phasedRegistrationNames: {
bubbled: keyOf({ onEmptied: true }),
captured: keyOf({ onEmptiedCapture: true })
}
},
encrypted: {
phasedRegistrationNames: {
bubbled: keyOf({ onEncrypted: true }),
captured: keyOf({ onEncryptedCapture: true })
}
},
ended: {
phasedRegistrationNames: {
bubbled: keyOf({ onEnded: true }),
captured: keyOf({ onEndedCapture: true })
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({ onError: true }),
captured: keyOf({ onErrorCapture: true })
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({ onFocus: true }),
captured: keyOf({ onFocusCapture: true })
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({ onInput: true }),
captured: keyOf({ onInputCapture: true })
}
},
invalid: {
phasedRegistrationNames: {
bubbled: keyOf({ onInvalid: true }),
captured: keyOf({ onInvalidCapture: true })
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyDown: true }),
captured: keyOf({ onKeyDownCapture: true })
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyPress: true }),
captured: keyOf({ onKeyPressCapture: true })
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyUp: true }),
captured: keyOf({ onKeyUpCapture: true })
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoad: true }),
captured: keyOf({ onLoadCapture: true })
}
},
loadedData: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedData: true }),
captured: keyOf({ onLoadedDataCapture: true })
}
},
loadedMetadata: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedMetadata: true }),
captured: keyOf({ onLoadedMetadataCapture: true })
}
},
loadStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadStart: true }),
captured: keyOf({ onLoadStartCapture: true })
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseDown: true }),
captured: keyOf({ onMouseDownCapture: true })
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseMove: true }),
captured: keyOf({ onMouseMoveCapture: true })
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOut: true }),
captured: keyOf({ onMouseOutCapture: true })
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOver: true }),
captured: keyOf({ onMouseOverCapture: true })
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseUp: true }),
captured: keyOf({ onMouseUpCapture: true })
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({ onPaste: true }),
captured: keyOf({ onPasteCapture: true })
}
},
pause: {
phasedRegistrationNames: {
bubbled: keyOf({ onPause: true }),
captured: keyOf({ onPauseCapture: true })
}
},
play: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlay: true }),
captured: keyOf({ onPlayCapture: true })
}
},
playing: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlaying: true }),
captured: keyOf({ onPlayingCapture: true })
}
},
progress: {
phasedRegistrationNames: {
bubbled: keyOf({ onProgress: true }),
captured: keyOf({ onProgressCapture: true })
}
},
rateChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onRateChange: true }),
captured: keyOf({ onRateChangeCapture: true })
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({ onReset: true }),
captured: keyOf({ onResetCapture: true })
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({ onScroll: true }),
captured: keyOf({ onScrollCapture: true })
}
},
seeked: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeked: true }),
captured: keyOf({ onSeekedCapture: true })
}
},
seeking: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeking: true }),
captured: keyOf({ onSeekingCapture: true })
}
},
stalled: {
phasedRegistrationNames: {
bubbled: keyOf({ onStalled: true }),
captured: keyOf({ onStalledCapture: true })
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({ onSubmit: true }),
captured: keyOf({ onSubmitCapture: true })
}
},
suspend: {
phasedRegistrationNames: {
bubbled: keyOf({ onSuspend: true }),
captured: keyOf({ onSuspendCapture: true })
}
},
timeUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onTimeUpdate: true }),
captured: keyOf({ onTimeUpdateCapture: true })
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchCancel: true }),
captured: keyOf({ onTouchCancelCapture: true })
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchEnd: true }),
captured: keyOf({ onTouchEndCapture: true })
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchMove: true }),
captured: keyOf({ onTouchMoveCapture: true })
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchStart: true }),
captured: keyOf({ onTouchStartCapture: true })
}
},
transitionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTransitionEnd: true }),
captured: keyOf({ onTransitionEndCapture: true })
}
},
volumeChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onVolumeChange: true }),
captured: keyOf({ onVolumeChangeCapture: true })
}
},
waiting: {
phasedRegistrationNames: {
bubbled: keyOf({ onWaiting: true }),
captured: keyOf({ onWaitingCapture: true })
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({ onWheel: true }),
captured: keyOf({ onWheelCapture: true })
}
}
};
var topLevelEventsToDispatchConfig = {
topAbort: eventTypes.abort,
topAnimationEnd: eventTypes.animationEnd,
topAnimationIteration: eventTypes.animationIteration,
topAnimationStart: eventTypes.animationStart,
topBlur: eventTypes.blur,
topCanPlay: eventTypes.canPlay,
topCanPlayThrough: eventTypes.canPlayThrough,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topDurationChange: eventTypes.durationChange,
topEmptied: eventTypes.emptied,
topEncrypted: eventTypes.encrypted,
topEnded: eventTypes.ended,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topInvalid: eventTypes.invalid,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topLoadedData: eventTypes.loadedData,
topLoadedMetadata: eventTypes.loadedMetadata,
topLoadStart: eventTypes.loadStart,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topPause: eventTypes.pause,
topPlay: eventTypes.play,
topPlaying: eventTypes.playing,
topProgress: eventTypes.progress,
topRateChange: eventTypes.rateChange,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSeeked: eventTypes.seeked,
topSeeking: eventTypes.seeking,
topStalled: eventTypes.stalled,
topSubmit: eventTypes.submit,
topSuspend: eventTypes.suspend,
topTimeUpdate: eventTypes.timeUpdate,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topTransitionEnd: eventTypes.transitionEnd,
topVolumeChange: eventTypes.volumeChange,
topWaiting: eventTypes.waiting,
topWheel: eventTypes.wheel
};
for (var type in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[type].dependencies = [type];
}
var ON_CLICK_KEY = keyOf({ onClick: null });
var onClickListeners = {};
var SimpleEventPlugin = {
eventTypes: eventTypes,
extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topAbort:
case topLevelTypes.topCanPlay:
case topLevelTypes.topCanPlayThrough:
case topLevelTypes.topDurationChange:
case topLevelTypes.topEmptied:
case topLevelTypes.topEncrypted:
case topLevelTypes.topEnded:
case topLevelTypes.topError:
case topLevelTypes.topInput:
case topLevelTypes.topInvalid:
case topLevelTypes.topLoad:
case topLevelTypes.topLoadedData:
case topLevelTypes.topLoadedMetadata:
case topLevelTypes.topLoadStart:
case topLevelTypes.topPause:
case topLevelTypes.topPlay:
case topLevelTypes.topPlaying:
case topLevelTypes.topProgress:
case topLevelTypes.topRateChange:
case topLevelTypes.topReset:
case topLevelTypes.topSeeked:
case topLevelTypes.topSeeking:
case topLevelTypes.topStalled:
case topLevelTypes.topSubmit:
case topLevelTypes.topSuspend:
case topLevelTypes.topTimeUpdate:
case topLevelTypes.topVolumeChange:
case topLevelTypes.topWaiting:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// Firefox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return null;
}
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topAnimationEnd:
case topLevelTypes.topAnimationIteration:
case topLevelTypes.topAnimationStart:
EventConstructor = SyntheticAnimationEvent;
break;
case topLevelTypes.topTransitionEnd:
EventConstructor = SyntheticTransitionEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
!EventConstructor ? "development" !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined;
var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
},
didPutListener: function (inst, registrationName, listener) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
if (registrationName === ON_CLICK_KEY) {
var id = inst._rootNodeID;
var node = ReactDOMComponentTree.getNodeFromInstance(inst);
if (!onClickListeners[id]) {
onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction);
}
}
},
willDeleteListener: function (inst, registrationName) {
if (registrationName === ON_CLICK_KEY) {
var id = inst._rootNodeID;
onClickListeners[id].remove();
delete onClickListeners[id];
}
}
};
module.exports = SimpleEventPlugin;
},{"110":110,"111":111,"113":113,"114":114,"115":115,"117":117,"118":118,"119":119,"120":120,"121":121,"122":122,"134":134,"15":15,"157":157,"164":164,"172":172,"176":176,"19":19,"43":43}],110:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticAnimationEvent
*/
'use strict';
var SyntheticEvent = _dereq_(114);
/**
* @interface Event
* @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
* @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
*/
var AnimationEventInterface = {
animationName: null,
elapsedTime: null,
pseudoElement: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface);
module.exports = SyntheticAnimationEvent;
},{"114":114}],111:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticClipboardEvent
*/
'use strict';
var SyntheticEvent = _dereq_(114);
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"114":114}],112:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticCompositionEvent
*/
'use strict';
var SyntheticEvent = _dereq_(114);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
module.exports = SyntheticCompositionEvent;
},{"114":114}],113:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticDragEvent
*/
'use strict';
var SyntheticMouseEvent = _dereq_(118);
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
},{"118":118}],114:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticEvent
*/
'use strict';
var PooledClass = _dereq_(25);
var assign = _dereq_(24);
var emptyFunction = _dereq_(164);
var warning = _dereq_(182);
var didWarnForAddedNewProperty = false;
var isProxySupported = typeof Proxy === 'function';
var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances'];
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {*} targetInst Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @param {DOMEventTarget} nativeEventTarget Target node.
*/
function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
if ("development" !== 'production') {
// these have a getter/setter for warnings
delete this.nativeEvent;
delete this.preventDefault;
delete this.stopPropagation;
}
this.dispatchConfig = dispatchConfig;
this._targetInst = targetInst;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
if ("development" !== 'production') {
delete this[propName]; // this has a getter/setter for warnings
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
return this;
}
assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if ("development" !== 'production') {
Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
} else {
this[propName] = null;
}
}
for (var i = 0; i < shouldBeReleasedProperties.length; i++) {
this[shouldBeReleasedProperties[i]] = null;
}
if ("development" !== 'production') {
var noop = _dereq_(164);
Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', noop));
Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', noop));
}
}
});
SyntheticEvent.Interface = EventInterface;
if ("development" !== 'production') {
if (isProxySupported) {
/*eslint-disable no-func-assign */
SyntheticEvent = new Proxy(SyntheticEvent, {
construct: function (target, args) {
return this.apply(target, Object.create(target.prototype), args);
},
apply: function (constructor, that, args) {
return new Proxy(constructor.apply(that, args), {
set: function (target, prop, value) {
if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) {
"development" !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
didWarnForAddedNewProperty = true;
}
target[prop] = value;
return true;
}
});
}
});
/*eslint-enable no-func-assign */
}
}
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function (Class, Interface) {
var Super = this;
var E = function () {};
E.prototype = Super.prototype;
var prototype = new E();
assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = assign({}, Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
module.exports = SyntheticEvent;
/**
* Helper to nullify syntheticEvent instance properties when destructing
*
* @param {object} SyntheticEvent
* @param {String} propName
* @return {object} defineProperty object
*/
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function';
return {
configurable: true,
set: set,
get: get
};
function set(val) {
var action = isFunction ? 'setting the method' : 'setting the property';
warn(action, 'This is effectively a no-op');
return val;
}
function get() {
var action = isFunction ? 'accessing the method' : 'accessing the property';
var result = isFunction ? 'This is a no-op function' : 'This is set to null';
warn(action, result);
return getVal;
}
function warn(action, result) {
var warningCondition = false;
"development" !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : undefined;
}
}
},{"164":164,"182":182,"24":24,"25":25}],115:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticFocusEvent
*/
'use strict';
var SyntheticUIEvent = _dereq_(121);
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"121":121}],116:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticInputEvent
*/
'use strict';
var SyntheticEvent = _dereq_(114);
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
module.exports = SyntheticInputEvent;
},{"114":114}],117:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticKeyboardEvent
*/
'use strict';
var SyntheticUIEvent = _dereq_(121);
var getEventCharCode = _dereq_(134);
var getEventKey = _dereq_(135);
var getEventModifierState = _dereq_(136);
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function (event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"121":121,"134":134,"135":135,"136":136}],118:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticMouseEvent
*/
'use strict';
var SyntheticUIEvent = _dereq_(121);
var ViewportMetrics = _dereq_(124);
var getEventModifierState = _dereq_(136);
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function (event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function (event) {
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
},
// "Proprietary" Interface.
pageX: function (event) {
return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function (event) {
return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"121":121,"124":124,"136":136}],119:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticTouchEvent
*/
'use strict';
var SyntheticUIEvent = _dereq_(121);
var getEventModifierState = _dereq_(136);
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"121":121,"136":136}],120:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticTransitionEvent
*/
'use strict';
var SyntheticEvent = _dereq_(114);
/**
* @interface Event
* @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
* @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
*/
var TransitionEventInterface = {
propertyName: null,
elapsedTime: null,
pseudoElement: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface);
module.exports = SyntheticTransitionEvent;
},{"114":114}],121:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticUIEvent
*/
'use strict';
var SyntheticEvent = _dereq_(114);
var getEventTarget = _dereq_(137);
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: function (event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target != null && target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function (event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"114":114,"137":137}],122:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule SyntheticWheelEvent
*/
'use strict';
var SyntheticMouseEvent = _dereq_(118);
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
},
deltaY: function (event) {
return 'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0;
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"118":118}],123:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Transaction
*/
'use strict';
var invariant = _dereq_(172);
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be run while it is already being run. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM updates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function () {
this.transactionWrappers = this.getTransactionWrappers();
if (this.wrapperInitData) {
this.wrapperInitData.length = 0;
} else {
this.wrapperInitData = [];
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function () {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked. The optional arguments helps prevent the need
* to bind in many cases.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} a Argument to pass to the method.
* @param {Object?=} b Argument to pass to the method.
* @param {Object?=} c Argument to pass to the method.
* @param {Object?=} d Argument to pass to the method.
* @param {Object?=} e Argument to pass to the method.
* @param {Object?=} f Argument to pass to the method.
*
* @return {*} Return value from `method`.
*/
perform: function (method, scope, a, b, c, d, e, f) {
!!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined;
var errorThrown;
var ret;
try {
this._isInTransaction = true;
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// one of these calls threw.
errorThrown = true;
this.initializeAll(0);
ret = method.call(scope, a, b, c, d, e, f);
errorThrown = false;
} finally {
try {
if (errorThrown) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
try {
this.closeAll(0);
} catch (err) {}
} else {
// Since `method` didn't throw, we don't want to silence the exception
// here.
this.closeAll(0);
}
} finally {
this._isInTransaction = false;
}
}
return ret;
},
initializeAll: function (startIndex) {
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
// The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function (startIndex) {
!this.isInTransaction() ? "development" !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined;
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var initData = this.wrapperInitData[i];
var errorThrown;
try {
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// wrapper.close threw.
errorThrown = true;
if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
wrapper.close.call(this, initData);
}
errorThrown = false;
} finally {
if (errorThrown) {
// The closer for wrapper i threw an error; close the remaining
// wrappers but silence any exceptions from them to ensure that the
// first error is the one to bubble up.
try {
this.closeAll(i + 1);
} catch (e) {}
}
}
}
this.wrapperInitData.length = 0;
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occurred.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
},{"172":172}],124:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ViewportMetrics
*/
'use strict';
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function (scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
},{}],125:[function(_dereq_,module,exports){
/**
* Copyright 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule accumulateInto
*/
'use strict';
var invariant = _dereq_(172);
/**
*
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
!(next != null) ? "development" !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined;
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current);
var nextIsArray = Array.isArray(next);
if (currentIsArray && nextIsArray) {
current.push.apply(current, next);
return current;
}
if (currentIsArray) {
current.push(next);
return current;
}
if (nextIsArray) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
},{"172":172}],126:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule adler32
*/
'use strict';
var MOD = 65521;
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
var a = 1;
var b = 0;
var i = 0;
var l = data.length;
var m = l & ~0x3;
while (i < m) {
var n = Math.min(i + 4096, m);
for (; i < n; i += 4) {
b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
}
a %= MOD;
b %= MOD;
}
for (; i < l; i++) {
b += a += data.charCodeAt(i);
}
a %= MOD;
b %= MOD;
return a | b << 16;
}
module.exports = adler32;
},{}],127:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule canDefineProperty
*/
'use strict';
var canDefineProperty = false;
if ("development" !== 'production') {
try {
Object.defineProperty({}, 'x', { get: function () {} });
canDefineProperty = true;
} catch (x) {
// IE will fail on defineProperty
}
}
module.exports = canDefineProperty;
},{}],128:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule createMicrosoftUnsafeLocalFunction
*/
/* globals MSApp */
'use strict';
/**
* Create a function which has 'unsafe' privileges (required by windows8 apps)
*/
var createMicrosoftUnsafeLocalFunction = function (func) {
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
return function (arg0, arg1, arg2, arg3) {
MSApp.execUnsafeLocalFunction(function () {
return func(arg0, arg1, arg2, arg3);
});
};
} else {
return func;
}
};
module.exports = createMicrosoftUnsafeLocalFunction;
},{}],129:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule dangerousStyleValue
*/
'use strict';
var CSSProperty = _dereq_(3);
var warning = _dereq_(182);
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
var styleWarnings = {};
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
if ("development" !== 'production') {
if (component) {
var owner = component._currentElement._owner;
var ownerName = owner ? owner.getName() : null;
if (ownerName && !styleWarnings[ownerName]) {
styleWarnings[ownerName] = {};
}
var warned = false;
if (ownerName) {
var warnings = styleWarnings[ownerName];
warned = warnings[name];
if (!warned) {
warnings[name] = true;
}
}
if (!warned) {
"development" !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : undefined;
}
}
}
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
},{"182":182,"3":3}],130:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule escapeTextContentForBrowser
*/
'use strict';
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'\'': '''
};
var ESCAPE_REGEX = /[&><"']/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextContentForBrowser;
},{}],131:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule findDOMNode
*/
'use strict';
var ReactCurrentOwner = _dereq_(38);
var ReactDOMComponentTree = _dereq_(43);
var ReactInstanceMap = _dereq_(75);
var getNativeComponentFromComposite = _dereq_(139);
var invariant = _dereq_(172);
var warning = _dereq_(182);
/**
* Returns the DOM node rendered by this element.
*
* @param {ReactComponent|DOMElement} componentOrElement
* @return {?DOMElement} The root node of this element.
*/
function findDOMNode(componentOrElement) {
if ("development" !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
"development" !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
var inst = ReactInstanceMap.get(componentOrElement);
if (inst) {
inst = getNativeComponentFromComposite(inst);
return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null;
}
if (typeof componentOrElement.render === 'function') {
!false ? "development" !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined;
} else {
!false ? "development" !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined;
}
}
module.exports = findDOMNode;
},{"139":139,"172":172,"182":182,"38":38,"43":43,"75":75}],132:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule flattenChildren
*/
'use strict';
var traverseAllChildren = _dereq_(153);
var warning = _dereq_(182);
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
var keyUnique = result[name] === undefined;
if ("development" !== 'production') {
"development" !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (keyUnique && child != null) {
result[name] = child;
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children == null) {
return children;
}
var result = {};
traverseAllChildren(children, flattenSingleChildIntoContext, result);
return result;
}
module.exports = flattenChildren;
},{"153":153,"182":182}],133:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule forEachAccumulated
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function (arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
};
module.exports = forEachAccumulated;
},{}],134:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventCharCode
*/
'use strict';
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
}
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
module.exports = getEventCharCode;
},{}],135:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventKey
*/
'use strict';
var getEventCharCode = _dereq_(134);
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
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'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
module.exports = getEventKey;
},{"134":134}],136:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventModifierState
*/
'use strict';
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
},{}],137:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getEventTarget
*/
'use strict';
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Normalize SVG <use> element events #4963
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
}
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
},{}],138:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getIteratorFn
*/
'use strict';
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
module.exports = getIteratorFn;
},{}],139:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getNativeComponentFromComposite
*/
'use strict';
var ReactNodeTypes = _dereq_(85);
function getNativeComponentFromComposite(inst) {
var type;
while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) {
inst = inst._renderedComponent;
}
if (type === ReactNodeTypes.NATIVE) {
return inst._renderedComponent;
} else if (type === ReactNodeTypes.EMPTY) {
return null;
}
}
module.exports = getNativeComponentFromComposite;
},{"85":85}],140:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getNodeForCharacterOffset
*/
'use strict';
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
},{}],141:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getTextContentAccessor
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"158":158}],142:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule getVendorPrefixedEventName
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
/**
* Generate a mapping of standard vendor prefixes using the defined style property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
function makePrefixMap(styleProp, eventName) {
var prefixes = {};
prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes['Webkit' + styleProp] = 'webkit' + eventName;
prefixes['Moz' + styleProp] = 'moz' + eventName;
prefixes['ms' + styleProp] = 'MS' + eventName;
prefixes['O' + styleProp] = 'o' + eventName.toLowerCase();
return prefixes;
}
/**
* A list of event names to a configurable list of vendor prefixes.
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
var prefixedEventNames = {};
/**
* Element to check for prefixes on.
*/
var style = {};
/**
* Bootstrap if a DOM exists.
*/
if (ExecutionEnvironment.canUseDOM) {
style = document.createElement('div').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 usable, and if not remove them from the map.
if (!('AnimationEvent' in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
}
// Same as above
if (!('TransitionEvent' in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return '';
}
module.exports = getVendorPrefixedEventName;
},{"158":158}],143:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule instantiateReactComponent
*/
'use strict';
var ReactCompositeComponent = _dereq_(37);
var ReactEmptyComponent = _dereq_(67);
var ReactNativeComponent = _dereq_(84);
var assign = _dereq_(24);
var invariant = _dereq_(172);
var warning = _dereq_(182);
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function (element) {
this.construct(element);
};
assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
_instantiateReactComponent: instantiateReactComponent
});
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
}
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node) {
var instance;
if (node === null || node === false) {
instance = ReactEmptyComponent.create(instantiateReactComponent);
} else if (typeof node === 'object') {
var element = node;
!(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? "development" !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined;
// Special case string values
if (typeof element.type === 'string') {
instance = ReactNativeComponent.createInternalComponent(element);
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// representations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
} else {
instance = new ReactCompositeComponentWrapper(element);
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactNativeComponent.createInstanceForText(node);
} else {
!false ? "development" !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined;
}
if ("development" !== 'production') {
"development" !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getNativeNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined;
}
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if ("development" !== 'production') {
instance._isOwnerNecessary = false;
instance._warnedAboutRefsInRender = false;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if ("development" !== 'production') {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
module.exports = instantiateReactComponent;
},{"172":172,"182":182,"24":24,"37":37,"67":67,"84":84}],144:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isEventSupported
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature = document.implementation && document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
},{"158":158}],145:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule isTextInputElement
*/
'use strict';
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea');
}
module.exports = isTextInputElement;
},{}],146:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule onlyChild
*/
'use strict';
var ReactElement = _dereq_(65);
var invariant = _dereq_(172);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection. The current implementation of this
* function assumes that a single child gets passed without a wrapper, but the
* purpose of this helper function is to abstract away the particular structure
* of children.
*
* @param {?object} children Child collection structure.
* @return {ReactComponent} The first and only `ReactComponent` contained in the
* structure.
*/
function onlyChild(children) {
!ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined;
return children;
}
module.exports = onlyChild;
},{"172":172,"65":65}],147:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule quoteAttributeValueForBrowser
*/
'use strict';
var escapeTextContentForBrowser = _dereq_(130);
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
module.exports = quoteAttributeValueForBrowser;
},{"130":130}],148:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule renderSubtreeIntoContainer
*/
'use strict';
var ReactMount = _dereq_(81);
module.exports = ReactMount.renderSubtreeIntoContainer;
},{"81":81}],149:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setInnerHTML
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
var createMicrosoftUnsafeLocalFunction = _dereq_(128);
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
node.innerHTML = html;
});
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function (node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
// in hopes that this is preserved even if "\uFEFF" is transformed to
// the actual Unicode character (by Babel, for example).
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
node.innerHTML = String.fromCharCode(0xFEFF) + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
}
module.exports = setInnerHTML;
},{"128":128,"158":158}],150:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule setTextContent
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
var escapeTextContentForBrowser = _dereq_(130);
var setInnerHTML = _dereq_(149);
/**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function (node, text) {
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function (node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
},{"130":130,"149":149,"158":158}],151:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shallowCompare
*/
'use strict';
var shallowEqual = _dereq_(181);
/**
* Does a shallow comparison for props and state.
* See ReactComponentWithPureRenderMixin
*/
function shallowCompare(instance, nextProps, nextState) {
return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState);
}
module.exports = shallowCompare;
},{"181":181}],152:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule shouldUpdateReactComponent
*/
'use strict';
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
if (prevEmpty || nextEmpty) {
return prevEmpty === nextEmpty;
}
var prevType = typeof prevElement;
var nextType = typeof nextElement;
if (prevType === 'string' || prevType === 'number') {
return nextType === 'string' || nextType === 'number';
} else {
return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
}
module.exports = shouldUpdateReactComponent;
},{}],153:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule traverseAllChildren
*/
'use strict';
var ReactCurrentOwner = _dereq_(38);
var ReactElement = _dereq_(65);
var getIteratorFn = _dereq_(138);
var invariant = _dereq_(172);
var warning = _dereq_(182);
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=:]/g;
var didWarnAboutMaps = false;
function userProvidedKeyEscaper(match) {
return userProvidedKeyEscaperLookup[match];
}
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (component && typeof component === 'object' && component.key != null) {
// Explicit key
return wrapUserProvidedKey(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* Escape a component key so that it is safe to use in a reactid.
*
* @param {*} text Component key to be escaped.
* @return {string} An escaped string.
*/
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper);
}
/**
* Wrap a `key` value explicitly provided by the user to distinguish it from
* implicitly-generated keys generated by a component's index in its parent.
*
* @param {string} key Value of a user-provided `key` attribute
* @return {string}
*/
function wrapUserProvidedKey(key) {
return '$' + escapeUserProvidedKey(key);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if ("development" !== 'production') {
"development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if ("development" !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
!false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined;
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
module.exports = traverseAllChildren;
},{"138":138,"172":172,"182":182,"38":38,"65":65}],154:[function(_dereq_,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule update
*/
/* global hasOwnProperty:true */
'use strict';
var assign = _dereq_(24);
var keyOf = _dereq_(176);
var invariant = _dereq_(172);
var hasOwnProperty = {}.hasOwnProperty;
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return assign(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = keyOf({ $push: null });
var COMMAND_UNSHIFT = keyOf({ $unshift: null });
var COMMAND_SPLICE = keyOf({ $splice: null });
var COMMAND_SET = keyOf({ $set: null });
var COMMAND_MERGE = keyOf({ $merge: null });
var COMMAND_APPLY = keyOf({ $apply: null });
var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function (command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
!Array.isArray(value) ? "development" !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined;
var specValue = spec[command];
!Array.isArray(specValue) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined;
}
function update(value, spec) {
!(typeof spec === 'object') ? "development" !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined;
if (hasOwnProperty.call(spec, COMMAND_SET)) {
!(Object.keys(spec).length === 1) ? "development" !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined;
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (hasOwnProperty.call(spec, COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
!(mergeObj && typeof mergeObj === 'object') ? "development" !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined;
!(nextValue && typeof nextValue === 'object') ? "development" !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined;
assign(nextValue, spec[COMMAND_MERGE]);
}
if (hasOwnProperty.call(spec, COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function (item) {
nextValue.push(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function (item) {
nextValue.unshift(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {
!Array.isArray(value) ? "development" !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined;
!Array.isArray(spec[COMMAND_SPLICE]) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
spec[COMMAND_SPLICE].forEach(function (args) {
!Array.isArray(args) ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
nextValue.splice.apply(nextValue, args);
});
}
if (hasOwnProperty.call(spec, COMMAND_APPLY)) {
!(typeof spec[COMMAND_APPLY] === 'function') ? "development" !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined;
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
},{"172":172,"176":176,"24":24}],155:[function(_dereq_,module,exports){
/**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule validateDOMNesting
*/
'use strict';
var assign = _dereq_(24);
var emptyFunction = _dereq_(164);
var warning = _dereq_(182);
var validateDOMNesting = emptyFunction;
if ("development" !== 'production') {
// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject', 'desc', 'title'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags = inScopeTags.concat(['button']);
// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
var emptyAncestorInfo = {
current: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
var updatedAncestorInfo = function (oldInfo, tag, instance) {
var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
var info = { tag: tag, instance: instance };
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
}
// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.current = info;
if (tag === 'form') {
ancestorInfo.formTag = info;
}
if (tag === 'a') {
ancestorInfo.aTagInScope = info;
}
if (tag === 'button') {
ancestorInfo.buttonTagInScope = info;
}
if (tag === 'nobr') {
ancestorInfo.nobrTagInScope = info;
}
if (tag === 'p') {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === 'li') {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === 'dd' || tag === 'dt') {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
/**
* Returns whether
*/
var isTagValidWithParent = function (tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case 'select':
return tag === 'option' || tag === 'optgroup' || tag === '#text';
case 'optgroup':
return tag === 'option' || tag === '#text';
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case 'option':
return tag === '#text';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case 'tr':
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case 'tbody':
case 'thead':
case 'tfoot':
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case 'colgroup':
return tag === 'col' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case 'table':
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case 'head':
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case 'html':
return tag === 'head' || tag === 'body';
case '#document':
return tag === 'html';
}
// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch (tag) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
case 'rp':
case 'rt':
return impliedEndTags.indexOf(parentTag) === -1;
case 'caption':
case 'col':
case 'colgroup':
case 'frame':
case 'head':
case 'html':
case 'tbody':
case 'td':
case 'tfoot':
case 'th':
case 'thead':
case 'tr':
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag == null;
}
return true;
};
/**
* Returns whether
*/
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
switch (tag) {
case 'address':
case 'article':
case 'aside':
case 'blockquote':
case 'center':
case 'details':
case 'dialog':
case 'dir':
case 'div':
case 'dl':
case 'fieldset':
case 'figcaption':
case 'figure':
case 'footer':
case 'header':
case 'hgroup':
case 'main':
case 'menu':
case 'nav':
case 'ol':
case 'p':
case 'section':
case 'summary':
case 'ul':
case 'pre':
case 'listing':
case 'table':
case 'hr':
case 'xmp':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return ancestorInfo.pTagInButtonScope;
case 'form':
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case 'li':
return ancestorInfo.listItemTagAutoclosing;
case 'dd':
case 'dt':
return ancestorInfo.dlItemTagAutoclosing;
case 'button':
return ancestorInfo.buttonTagInScope;
case 'a':
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case 'nobr':
return ancestorInfo.nobrTagInScope;
}
return null;
};
/**
* Given a ReactCompositeComponent instance, return a list of its recursive
* owners, starting at the root and ending with the instance itself.
*/
var findOwnerStack = function (instance) {
if (!instance) {
return [];
}
var stack = [];
do {
stack.push(instance);
} while (instance = instance._currentElement._owner);
stack.reverse();
return stack;
};
var didWarn = {};
validateDOMNesting = function (childTag, childInstance, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var problematic = invalidParent || invalidAncestor;
if (problematic) {
var ancestorTag = problematic.tag;
var ancestorInstance = problematic.instance;
var childOwner = childInstance && childInstance._currentElement._owner;
var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
var childOwners = findOwnerStack(childOwner);
var ancestorOwners = findOwnerStack(ancestorOwner);
var minStackLen = Math.min(childOwners.length, ancestorOwners.length);
var i;
var deepestCommon = -1;
for (i = 0; i < minStackLen; i++) {
if (childOwners[i] === ancestorOwners[i]) {
deepestCommon = i;
} else {
break;
}
}
var UNKNOWN = '(unknown)';
var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ownerInfo = [].concat(
// If the parent and child instances have a common owner ancestor, start
// with that -- otherwise we just start with the parent's owners.
deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag,
// If we're warning about an invalid (non-parent) ancestry, add '...'
invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > ');
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo;
if (didWarn[warnKey]) {
return;
}
didWarn[warnKey] = true;
var tagDisplayName = childTag;
if (childTag !== '#text') {
tagDisplayName = '<' + childTag + '>';
}
if (invalidParent) {
var info = '';
if (ancestorTag === 'table' && childTag === 'tr') {
info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
}
"development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' + 'See %s.%s', tagDisplayName, ancestorTag, ownerInfo, info) : undefined;
} else {
"development" !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : undefined;
}
}
};
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
// For testing
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
},{"164":164,"182":182,"24":24}],156:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var invariant = _dereq_(172);
/**
* The CSSCore module specifies the API (and implements most of the methods)
* that should be used when dealing with the display of elements (via their
* CSS classes and visibility on screen. It is an API focused on mutating the
* display and not reading it as no logical state should be encoded in the
* display of elements.
*/
var CSSCore = {
/**
* Adds the class passed in to the element if it doesn't already have it.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
addClass: function (element, className) {
!!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.add(className);
} else if (!CSSCore.hasClass(element, className)) {
element.className = element.className + ' ' + className;
}
}
return element;
},
/**
* Removes the class passed in from the element
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
removeClass: function (element, className) {
!!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.remove(className);
} else if (CSSCore.hasClass(element, className)) {
element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one
.replace(/^\s*|\s*$/g, ''); // trim the ends
}
}
return element;
},
/**
* Helper to add or remove a class from an element based on a condition.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @param {*} bool condition to whether to add or remove the class
* @return {DOMElement} the element passed in
*/
conditionClass: function (element, className, bool) {
return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
},
/**
* Tests whether the element has the class specified.
*
* @param {DOMNode|DOMWindow} element the element to set the class on
* @param {string} className the CSS className
* @return {boolean} true if the element has the class, false if not
*/
hasClass: function (element, className) {
!!/\s/.test(className) ? "development" !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined;
if (element.classList) {
return !!className && element.classList.contains(className);
}
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
}
};
module.exports = CSSCore;
},{"172":172}],157:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, 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.
*
* @typechecks
*/
var emptyFunction = _dereq_(164);
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
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 (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function () {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function () {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture 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.
*/
capture: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function () {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if ("development" !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function () {}
};
module.exports = EventListener;
},{"164":164}],158:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
},{}],159:[function(_dereq_,module,exports){
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
},{}],160:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var camelize = _dereq_(159);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
},{"159":159}],161:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var isTextNode = _dereq_(174);
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
},{"174":174}],162:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var invariant = _dereq_(172);
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browsers builtin objects can report typeof 'function' (e.g. NodeList
// in old versions of Safari).
!(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? "development" !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined;
!(typeof length === 'number') ? "development" !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined;
!(length === 0 || length - 1 in obj) ? "development" !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined;
!(typeof obj.callee !== 'function') ? "development" !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : undefined;
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return(
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
},{"172":172}],163:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
var ExecutionEnvironment = _dereq_(158);
var createArrayFromMixed = _dereq_(162);
var getMarkupWrap = _dereq_(168);
var invariant = _dereq_(172);
/**
* Dummy container used to render all markup.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
!!!dummyNode ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined;
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
!handleScript ? "development" !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined;
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = Array.from(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"158":158,"162":162,"168":168,"172":172}],164:[function(_dereq_,module,exports){
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
function emptyFunction() {}
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
},{}],165:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyObject = {};
if ("development" !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],166:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
},{}],167:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*/
function getActiveElement() /*?DOMElement*/{
if (typeof document === 'undefined') {
return null;
}
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
},{}],168:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*eslint-disable fb-www/unsafe-html */
var ExecutionEnvironment = _dereq_(158);
var invariant = _dereq_(172);
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>'];
var markupWrap = {
'*': [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': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap
};
// Initialize the SVG elements since we know they'll always need to be wrapped
// consistently. If they are created inside a <div> they will be initialized in
// the wrong namespace (and will not display).
var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan'];
svgElements.forEach(function (nodeName) {
markupWrap[nodeName] = svgWrap;
shouldWrap[nodeName] = true;
});
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
!!!dummyNode ? "development" !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined;
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
},{"158":158,"172":172}],169:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
},{}],170:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],171:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var hyphenate = _dereq_(170);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
},{"170":170}],172:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if ("development" !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
},{}],173:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
function isNode(object) {
return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
}
module.exports = isNode;
},{}],174:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var isNode = _dereq_(173);
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
},{"173":173}],175:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks static-only
*/
'use strict';
var invariant = _dereq_(172);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function (obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? "development" !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"172":172}],176:[function(_dereq_,module,exports){
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
var keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
},{}],177:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Executes the provided `callback` once for each enumerable own property in the
* object and constructs a new object from the results. The `callback` is
* invoked with three arguments:
*
* - the property value
* - the property name
* - the object being traversed
*
* Properties that are added after the call to `mapObject` will not be visited
* by `callback`. If the values of existing properties are changed, the value
* passed to `callback` will be the value at the time `mapObject` visits them.
* Properties that are deleted before being visited are not visited.
*
* @grep function objectMap()
* @grep function objMap()
*
* @param {?object} object
* @param {function} callback
* @param {*} context
* @return {?object}
*/
function mapObject(object, callback, context) {
if (!object) {
return null;
}
var result = {};
for (var name in object) {
if (hasOwnProperty.call(object, name)) {
result[name] = callback.call(context, object[name], name, object);
}
}
return result;
}
module.exports = mapObject;
},{}],178:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks static-only
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
},{}],179:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
'use strict';
var ExecutionEnvironment = _dereq_(158);
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.msPerformance || window.webkitPerformance;
}
module.exports = performance || {};
},{"158":158}],180:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*/
var performance = _dereq_(179);
var performanceNow;
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (performance.now) {
performanceNow = function () {
return performance.now();
};
} else {
performanceNow = function () {
return Date.now();
};
}
module.exports = performanceNow;
},{"179":179}],181:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
*
*/
/*eslint-disable no-self-compare */
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* 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 (is(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.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],182:[function(_dereq_,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyFunction = _dereq_(164);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("development" !== 'production') {
warning = function (condition, format) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
}
};
}
module.exports = warning;
},{"164":164}]},{},[106])(106)
}); |
app/src/assets/js/components/global/club-linked-logo.js | Huskie/ScottishPremiershipData | import React from 'react';
import { Link } from 'react-router';
class ClubLinkedLogoComponent extends React.Component {
constructor (props) {
super(props);
}
render() {
return (
<div className="club-linked-logo">
<Link className="club-linked-logo__link" to={"/clubs/" + this.props.slug} title={this.props.name + " club page"}>
<img alt={this.props.name + " club badge"} className="club-linked-logo__image" src={"/assets/img/logos/" + this.props.nation + "/" + this.props.slug + ".png"} />
</Link>
</div>
)
}
}
ClubLinkedLogoComponent.defaultProps = {};
ClubLinkedLogoComponent.displayName = 'ClubLinkedLogoComponent';
ClubLinkedLogoComponent.propTypes = {};
export default ClubLinkedLogoComponent; |
ajax/libs/mediaelement/2.1.4/jquery.js | zhengyongbo/cdnjs | /*!
* jQuery JavaScript Library v1.5.1rc1
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Fri Feb 18 13:57:25 2011 -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, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// 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 deferred used on DOM ready
readyList,
// Promise methods
promiseMethods = "then done fail isResolved isRejected promise".split( " " ),
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = "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] ) {
context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.5.1rc1",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.done( 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 || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
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
readyList.resolveWith( 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 );
}
},
// Cross-browser xml parsing
// (xml & tmp used internally)
parseXML: function( data , xml , tmp ) {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
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.head || document.getElementsByTagName( "head" )[0] || document.documentElement,
script = document.createElement( "script" );
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;
}
}
// Flatten any nested arrays
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();
},
// Create a simple deferred (one callbacks list)
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( jQuery.isFunction( this.promise ) ? this.promise() : this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
// Full fledged deferred (two callbacks list)
Deferred: function( func ) {
var deferred = jQuery._Deferred(),
failDeferred = jQuery._Deferred(),
promise;
// Add errorDeferred methods, then and promise
jQuery.extend( deferred, {
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj , i /* internal */ ) {
if ( obj == null ) {
if ( promise ) {
return promise;
}
promise = obj = {};
}
i = promiseMethods.length;
while( i-- ) {
obj[ promiseMethods[ i ] ] = deferred[ promiseMethods[ i ] ];
}
return obj;
}
} );
// Make sure only one callback list will be used
deferred.then( failDeferred.cancel, deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
return deferred;
},
// Deferred helper
when: function( object ) {
var args = arguments,
length = args.length,
deferred = length <= 1 && object && jQuery.isFunction( object.promise ) ?
object :
jQuery.Deferred(),
promise = deferred.promise(),
resolveArray;
if ( length > 1 ) {
resolveArray = new Array( length );
jQuery.each( args, function( index, element ) {
jQuery.when( element ).then( function( value ) {
resolveArray[ index ] = arguments.length > 1 ? slice.call( arguments, 0 ) : value;
if( ! --length ) {
deferred.resolveWith( promise, resolveArray );
}
}, deferred.reject );
} );
} else if ( deferred !== object ) {
deferred.resolve( object );
}
return promise;
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySubclass( selector, context ) {
return new jQuerySubclass.fn.init( selector, context );
}
jQuery.extend( true, jQuerySubclass, this );
jQuerySubclass.superclass = this;
jQuerySubclass.fn = jQuerySubclass.prototype = this();
jQuerySubclass.fn.constructor = jQuerySubclass;
jQuerySubclass.subclass = this.subclass;
jQuerySubclass.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) {
context = jQuerySubclass(context);
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass );
};
jQuerySubclass.fn.init.prototype = jQuerySubclass.fn;
var rootjQuerySubclass = jQuerySubclass(document);
return jQuerySubclass;
},
browser: {}
});
// Create readyList deferred
readyList = jQuery._Deferred();
// 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 );
};
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
// Expose jQuery to the global object
return jQuery;
})();
(function() {
jQuery.support = {};
var div = document.createElement("div");
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,
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;
var _scriptEval = null;
jQuery.support.scriptEval = function() {
if ( _scriptEval === null ) {
var root = document.documentElement,
script = document.createElement("script"),
id = "script" + jQuery.now();
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 ] ) {
_scriptEval = true;
delete window[ id ];
} else {
_scriptEval = false;
}
root.removeChild( script );
// release memory in IE
root = script = id = null;
}
return _scriptEval;
};
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch(e) {
jQuery.support.deleteExpando = false;
}
if ( !div.addEventListener && 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"),
body = document.getElementsByTagName("body")[0];
// Frameset documents with no body should not run this code
if ( !body ) {
return;
}
div.style.width = div.style.paddingLeft = "1px";
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;border: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 = "";
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;
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( !el.attachEvent ) {
return true;
}
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
div = all = a = null;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
} else {
id = jQuery.expando;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
} else {
cache[ id ] = jQuery.extend(cache[ id ], name);
}
}
thisCache = cache[ id ];
// Internal jQuery data is stored in a separate object inside the object's data
// cache in order to avoid key collisions between internal data and user-defined
// data
if ( pvt ) {
if ( !thisCache[ internalKey ] ) {
thisCache[ internalKey ] = {};
}
thisCache = thisCache[ internalKey ];
}
if ( data !== undefined ) {
thisCache[ name ] = data;
}
// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
// not attempt to inspect the internal events object using jQuery.data, as this
// internal data object is undocumented and subject to change.
if ( name === "events" && !thisCache[name] ) {
return thisCache[ internalKey ] && thisCache[ internalKey ].events;
}
return getByName ? thisCache[ name ] : thisCache;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
if ( thisCache ) {
delete thisCache[ name ];
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !isEmptyDataObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( pvt ) {
delete cache[ id ][ internalKey ];
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
var internalCache = cache[ id ][ internalKey ];
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
if ( jQuery.support.deleteExpando || cache != window ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the entire user cache at once because it's faster than
// iterating through each key, but we need to continue to persist internal
// data if it existed
if ( internalCache ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
cache[ id ][ internalKey ] = internalCache;
// Otherwise, we need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
} else if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
} else {
elem[ jQuery.expando ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 ) {
var attr = this[0].attributes, name;
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;
}
// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
// property to be considered empty objects; this property always exists in
// order to make sure JSON.stringify does not expose internal metadata
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
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);
});
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue", true );
}
}
});
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\r]/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 );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
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 get/set attributes on text, comment and attribute nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) {
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;
// Only do all the following if this is a node (faster for style)
if ( elem.nodeType === 1 ) {
// 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;
}
// Handle everything which isn't a DOM element node
if ( set ) {
elem[ name ] = value;
}
return elem[ name ];
}
});
var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspace = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
};
/*
* 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;
}
// TODO :: Use a try/catch until it's safe to pull this out (likely 1.6)
// Minor release fix for bug #8018
try {
// 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;
}
}
catch ( e ) {}
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;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
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,
elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData.events;
if ( !elemData || !events ) {
return;
}
// 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 ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem, undefined, true );
}
}
},
// 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 ] ) {
// XXX This code smells terrible. event.js should not be directly
// inspecting the data cache
jQuery.each( jQuery.cache, function() {
// internalKey variable is just used to make it easier to find
// and potentially change this stuff later; currently it just
// points to jQuery.expando
var internalKey = jQuery.expando,
internalCache = this[ internalKey ];
if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
jQuery.event.trigger( event, data, internalCache.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 = jQuery._data( elem, "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, "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;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// 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 {
// Chrome does something similar, the parentNode property
// can be accessed but is null.
if ( parent !== document && !parent.parentNode ) {
return;
}
// 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 && 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 ) {
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 ) {
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;
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" ) {
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" ) {
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 ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
// Don't pass args or remember liveFired; they apply to the donor event.
var event = jQuery.extend( {}, args[ 0 ] );
event.type = type;
event.originalEvent = {};
event.liveFired = undefined;
jQuery.event.handle.call( elem, event );
if ( event.isDefaultPrevented() ) {
args[ 0 ].preventDefault();
}
}
// Create "bubbling" focus and blur events
if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
jQuery.event.special[ fix ] = {
setup: function() {
this.addEventListener( orig, handler, true );
},
teardown: function() {
this.removeEventListener( orig, handler, true );
}
};
function handler( e ) {
e = jQuery.event.fix( e );
e.type = fix;
return jQuery.event.handle.call( this, e );
}
});
}
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, "events" );
// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
if ( event.liveFired === this || !events || !events.live || event.target.disabled || 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 )) && !close.elem.disabled ) {
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;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, 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,
rBackslash = /\\/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} 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( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
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|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return "text" === elem.getAttribute( '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( 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;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector,
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,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var 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 ) :
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 ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.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
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
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( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !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, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || (l > 1 && i < lastIndex) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var internalKey = jQuery.expando,
oldData = jQuery.data( src ),
curData = jQuery.data( dest, oldData );
// Switch to use the internal data object, if it exists, for the next
// stage of data copying
if ( (oldData = oldData[ internalKey ]) ) {
var events = oldData.events;
curData = curData[ internalKey ] = jQuery.extend({}, oldData);
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
}
}
function cloneFixAttributes(src, dest) {
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
var nodeName = dest.nodeName.toLowerCase();
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
dest.clearAttributes();
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
dest.mergeAttributes(src);
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
args[0].charAt(0) === "<" && !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({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var clone = elem.cloneNode(true),
srcElements,
destElements,
i;
if ( !jQuery.support.noCloneEvent && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName
// instead
srcElements = elem.getElementsByTagName("*");
destElements = clone.getElementsByTagName("*");
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents && "getElementsByTagName" in elem ) {
srcElements = elem.getElementsByTagName("*");
destElements = clone.getElementsByTagName("*");
if ( srcElements.length ) {
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
}
// Return the cloned set
return clone;
},
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, internalKey = jQuery.expando, 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 ] && cache[ id ][ internalKey ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
}
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,
ret = elem.currentStyle && elem.currentStyle[ name ],
rsLeft = elem.runtimeStyle && elem.runtimeStyle[ 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;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
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 r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /(?:^file|^widget|\-extension):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rucHeaders = /(^|\-)([a-z])/g,
rucHeadersFunc = function( _, $1, $2 ) {
return $1 + $2.toUpperCase();
},
rurl = /^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts;
// #8138, IE may throw an exception when accessing
// a field from document.location if document.domain has been set
try {
ajaxLocation = document.location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() );
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
//Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for(; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.bind( o, f );
};
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
} );
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function ( target, settings ) {
if ( !settings ) {
// Only one parameter, we extend ajaxSettings
settings = target;
target = jQuery.extend( true, jQuery.ajaxSettings, settings );
} else {
// target was provided, we extend into it
jQuery.extend( true, target, jQuery.ajaxSettings, settings );
}
// Flatten fields we don't want deep extended
for( var field in { context: 1, url: 1 } ) {
if ( field in settings ) {
target[ field ] = settings[ field ];
} else if( field in jQuery.ajaxSettings ) {
target[ field ] = jQuery.ajaxSettings[ field ];
}
}
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
crossDomain: null,
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": "*/*"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery._Deferred(),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, statusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status ? 4 : 0;
var isSuccess,
success,
error,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = statusText;
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( !s.crossDomain ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
requestHeaders[ "Content-Type" ] = s.contentType;
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
}
if ( jQuery.etag[ ifModifiedKey ] ) {
requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
}
}
// Set the Accepts header for the server, depending on the dataType
requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
s.accepts[ "*" ];
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( status < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
jQuery.error( e );
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) && 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 we see an array here, it is empty and should be treated as an empty
// object
if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
add( prefix, "" );
// Serialize object item.
} else {
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for( key in s.converters ) {
if( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|()\?\?()/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var dataIsString = ( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
originalSettings.jsonpCallback ||
originalSettings.jsonp != null ||
s.jsonp !== false && ( jsre.test( s.url ) ||
dataIsString && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2",
cleanUp = function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
};
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( dataIsString ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Install cleanUp function
jqXHR.then( cleanUp, cleanUp );
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
} );
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
} );
var // #5280: next active xhr id and list of active xhrs' callbacks
xhrId = jQuery.now(),
xhrCallbacks,
// XHR used to determine supports properties
testXHR;
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
function xhrOnUnloadAbort() {
jQuery( window ).unload(function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Test if we can create an xhr object
testXHR = jQuery.ajaxSettings.xhr();
jQuery.support.ajax = !!testXHR;
// Does this browser support crossDomain XHR requests
jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
// No need for the temporary xhr anymore
testXHR = undefined;
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// Requested-With header
// Not set for crossDomain requests with no content
// (see why at http://trac.dojotoolkit.org/ticket/9486)
// Won't change header if already provided
if ( !( s.crossDomain && !s.hasContent ) && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
delete xhrCallbacks[ handle ];
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
xhrOnUnloadAbort();
}
// Add to list of active xhrs callbacks
handle = xhrId++;
xhr.onreadystatechange = xhrCallbacks[ handle ] = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
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" ) ) {
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();
if ( parts ) {
var end = parseFloat( parts[2] ),
unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "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 parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = jQuery.now();
this.start = from;
this.end = to;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "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: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
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
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ];
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.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.jQuery = window.$ = jQuery;
})(window); |
src/component/home/index.js | Cadburylion/personal-portfolio | import React from 'react'
import ReactDom from 'react-dom'
import {connect} from 'react-redux'
import {withRouter} from 'react-router'
import {NavLink} from 'react-router-dom'
import FontAwesome from 'react-fontawesome'
import * as viewActions from '../../action/viewActions.js'
import * as route from '../../action/route.js'
import './styles.scss'
class Home extends React.Component{
constructor(props){
super(props)
this.state={
hover: '',
route: '',
}
this.exit = this.exit.bind(this)
this.reload = this.reload.bind(this)
this.onEnter = this.onEnter.bind(this)
this.onLeave = this.onLeave.bind(this)
this.handleCover = this.handleCover.bind(this)
this.selectRoute = this.selectRoute.bind(this)
this.changeBackground = this.changeBackground.bind(this)
}
handleCover(toggle){
this.props.handleCover('COVER_TOGGLE')
}
onEnter(skill) {
this.setState({
hover: skill,
})
}
onLeave(){
this.setState({
hover: '',
})
}
selectRoute(route){
if(route === '/about'){this.setState({route: '/about'})}
if(route === '/portfolio'){this.setState({route: '/portfolio'})}
if(route === '/contact'){this.setState({route: '/contact'})}
}
exit(){
setTimeout(this.reload, 100)
}
reload(){
location.reload()
}
changeBackground(){
let {backgrounds, background} = this.props.backgrounds
let nextBackgrounds = [background, ...backgrounds]
let nextBackground = nextBackgrounds.pop()
let backgroundObject = {
backgrounds: nextBackgrounds,
background: nextBackground,
}
this.props.changeBackground(backgroundObject)
}
render(){
return(
<div className={`home-main ${this.props.lightTheme ? 'home-main-light' : ''}`}>
<div className={'dashboard-nav'}>
<NavLink exact to='/about' activeClassName='active' className={`to-about nav`}>
About
</NavLink>
<NavLink exact to={'/portfolio'} activeClassName='active' className='to-portfolio nav' >
Portfolio
</NavLink>
<NavLink exact to={'/contact'} activeClassName='active' className={'to-contact nav'}>
Contact
</NavLink>
<NavLink exact to={'/'} activeClassName='' className={'to-landing nav'}>
Clear
</NavLink>
<NavLink exact to={'/'} activeClassName='' className={'explore nav'} onClick={this.changeBackground}>
Explore
</NavLink>
<NavLink exact to={'/'} activeClassName='' className={'to-start nav'} onClick={this.exit}>
Exit
</NavLink>
</div>
<div className='hovered-skill'>{this.state.hover}</div>
<div className='skill-icon-container'>
<div className='skill-icon javascript' onMouseEnter={()=>this.onEnter('JavaScript')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/javascript-original.svg')} alt='javascript logo' />
</div>
<div className='skill-icon react' onMouseEnter={()=>this.onEnter('React')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/react-original.svg')} alt='react logo' />
</div>
<div className='skill-icon redux' onMouseEnter={()=>this.onEnter('Redux')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/redux.svg')} alt='redux logo' />
</div>
<div className='skill-icon html' onMouseEnter={()=>this.onEnter('HTML5')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/html5-original.svg')} alt='html 5 logo'/>
</div>
<div className='skill-icon css' onMouseEnter={()=>this.onEnter('CSS3')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/css3-original.svg')} alt='css 3 logo' />
</div>
<div className='skill-icon sass' onMouseEnter={()=>this.onEnter('Sass')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/sass-original.svg')} alt='sass logo' />
</div>
<div className='skill-icon node' onMouseEnter={()=>this.onEnter('Node')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/nodejs-original.svg')} alt='node logo' />
</div>
<div className='skill-icon mongodb' onMouseEnter={()=>this.onEnter('MongoDB')} onMouseLeave={this.onLeave}>
<img src={require('../../assets/mongodb-original.svg')} alt='mongo db logo'/>
</div>
</div>
</div>
)
}
}
let mapStateToProps = (state) => ({
lightTheme: state.lightTheme,
route: state.route,
backgrounds: state.setBackground,
})
let mapDispatchToProps = (dispatch) => ({
handleCover: (toggle) => dispatch(viewActions.cover(toggle)),
changeBackground: (obj) => dispatch(viewActions.background(obj)),
enterSite: (bool) => dispatch(viewActions.entered(bool)),
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Home))
|
src/routes/Home/components/HomeView.js | MichalObi/redux-to-do-app | 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
|
ajax/libs/rxjs/2.2.26/rx.js | AMoo-Miki/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
identity = Rx.helpers.identity = function (x) { return x; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) ||
'_es6shim_iterator_';
// Firefox ships a partial implementation using the name @@iterator.
// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
// So use that name if we detect it.
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var BooleanDisposable = (function () {
function BooleanDisposable (isSingle) {
this.isSingle = isSingle;
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
if (this.current && this.isSingle) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
inherits(SingleAssignmentDisposable, super_);
function SingleAssignmentDisposable() {
super_.call(this, true);
}
return SingleAssignmentDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
var SerialDisposable = Rx.SerialDisposable = (function (super_) {
inherits(SerialDisposable, super_);
function SerialDisposable() {
super_.call(this, false);
}
return SerialDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
/**
* @constructor
* @private
*/
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchException = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @private */
var CatchScheduler = (function (_super) {
function localNow() {
return this._scheduler.now();
}
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, _super);
/** @private */
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
/** @private */
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
/** @private */
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
/** @private */
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
/** @private */
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @private */
var ObserveOnObserver = (function (_super) {
inherits(ObserveOnObserver, _super);
/** @private */
function ObserveOnObserver() {
_super.apply(this, arguments);
}
/** @private */
ObserveOnObserver.prototype.next = function (value) {
_super.prototype.next.call(this, value);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.error = function (e) {
_super.prototype.error.call(this, e);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.completed = function () {
_super.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
return function () {
if (promise && promise.abort) {
promise.abort();
}
}
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an iterable into an Observable sequence
*
* @example
* var res = Rx.Observable.fromIterable(new Map());
* var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence.
*/
Observable.fromIterable = function (iterable, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var iterator;
try {
iterator = iterable[$iterator$]();
} catch (e) {
observer.onError(e);
return;
}
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = iterator.next();
} catch (err) {
observer.onError(err);
return;
}
if (next.done) {
observer.onCompleted();
} else {
observer.onNext(next.value);
self();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == null) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throwException(new Error('Error'));
* var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
if (resource) {
disposable = resource;
}
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
if (isPromise(xs)) { xs = observableFromPromise(xs); }
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) { observer.onCompleted(); }
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) { observer.onCompleted(); }
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) {
throw new Error('Second observable is required');
}
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
self();
}, function () {
self();
}));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.doAction(observer);
* var res = observable.doAction(onNext);
* var res = observable.doAction(onNext, onError);
* var res = observable.doAction(onNext, onError, onCompleted);
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(42);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* var res = source.takeLast(5);
* var res = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
if (count <= 0) {
throw new Error(argumentOutOfRange);
}
if (arguments.length === 1) {
skip = count;
}
if (skip <= 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [],
createWindow = function () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
};
createWindow();
m.setDisposable(source.subscribe(function (x) {
var s;
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
var c = n - count + 1;
if (c >= 0 && c % skip === 0) {
s = q.shift();
s.onCompleted();
}
n++;
if (n % skip === 0) {
createWindow();
}
}, function (exception) {
while (q.length > 0) {
q.shift().onError(exception);
}
observer.onError(exception);
}, function () {
while (q.length > 0) {
q.shift().onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
function concatMap(selector) {
return this.map(function (x, i) {
var result = selector(x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
function concatMapObserver(onNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
observer.onNext(onNext(x, index++));
},
function (err) {
observer.onNext(onError(err));
observer.completed();
},
function () {
observer.onNext(onCompleted());
observer.onCompleted();
});
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
if (typeof selector === 'function') {
return concatMap.call(this, selector);
}
return concatMap.call(this, function () {
return selector;
});
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, keySerializer) {
var source = this;
keySelector || (keySelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var hashSet = {};
return source.subscribe(function (x) {
var key, serializedKey, otherKey, hasMatch = false;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (exception) {
observer.onError(exception);
return;
}
for (otherKey in hashSet) {
if (serializedKey === otherKey) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
hashSet[serializedKey] = null;
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, keySerializer) {
return this.groupByUntil(keySelector, elementSelector, function () {
return observableNever();
}, keySerializer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) {
var source = this;
elementSelector || (elementSelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var map = {},
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
fireNewMapEntry = false;
try {
writer = map[serializedKey];
if (!writer) {
writer = new Subject();
map[serializedKey] = writer;
fireNewMapEntry = true;
}
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
if (fireNewMapEntry) {
group = new GroupedObservable(key, writer, refCountDisposable);
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
observer.onNext(group);
md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
if (serializedKey in map) {
delete map[serializedKey];
writer.onCompleted();
}
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(noop, function (exn) {
for (w in map) {
map[w].onError(exn);
}
observer.onError(exn);
}, function () {
expire();
}));
}
try {
element = elementSelector(x);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
for (var w in map) {
map[w].onError(ex);
}
observer.onError(ex);
}, function () {
for (var w in map) {
map[w].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function selectMany(selector) {
return this.select(function (x, i) {
var result = selector(x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
function selectManyObserver(onNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
observer.onNext(onNext(x, index++));
},
function (err) {
observer.onNext(onError(err));
observer.completed();
},
function () {
observer.onNext(onCompleted());
observer.onCompleted();
});
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.select(function (y) {
return resultSelector(x, y, i);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (typeof subscriber === 'undefined') {
subscriber = disposableEmpty;
} else if (typeof subscriber === 'function') {
subscriber = disposableCreate(subscriber);
}
return subscriber;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var GroupedObservable = (function (_super) {
inherits(GroupedObservable, _super);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
/**
* @constructor
* @private
*/
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
_super.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
react/features/conference/components/AbstractConference.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import { NotificationsContainer } from '../../notifications/components';
import { shouldDisplayTileView } from '../../video-layout';
import { shouldDisplayNotifications } from '../functions';
/**
* The type of the React {@code Component} props of {@link AbstractLabels}.
*/
export type AbstractProps = {
/**
* Set to {@code true} when the notifications are to be displayed.
*
* @protected
* @type {boolean}
*/
_notificationsVisible: boolean,
/**
* Conference room name.
*
* @protected
* @type {string}
*/
_room: string,
/**
* Whether or not the layout should change to support tile view mode.
*
* @protected
* @type {boolean}
*/
_shouldDisplayTileView: boolean
};
/**
* A container to hold video status labels, including recording status and
* current large video quality.
*
* @augments Component
*/
export class AbstractConference<P: AbstractProps, S>
extends Component<P, S> {
/**
* Renders the {@code LocalRecordingLabel}.
*
* @param {Object} props - The properties to be passed to
* the {@code NotificationsContainer}.
* @protected
* @returns {React$Element}
*/
renderNotificationsContainer(props: ?Object) {
if (this.props._notificationsVisible) {
return (
React.createElement(NotificationsContainer, props)
);
}
return null;
}
}
/**
* Maps (parts of) the redux state to the associated props of the {@link Labels}
* {@code Component}.
*
* @param {Object} state - The redux state.
* @private
* @returns {AbstractProps}
*/
export function abstractMapStateToProps(state: Object) {
return {
_notificationsVisible: shouldDisplayNotifications(state),
_room: state['features/base/conference'].room,
_shouldDisplayTileView: shouldDisplayTileView(state)
};
}
|
src/svg-icons/action/important-devices.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionImportantDevices = (props) => (
<SvgIcon {...props}>
<path d="M23 11.01L18 11c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-9c0-.55-.45-.99-1-.99zM23 20h-5v-7h5v7zM20 2H2C.89 2 0 2.89 0 4v12c0 1.1.89 2 2 2h7v2H7v2h8v-2h-2v-2h2v-2H2V4h18v5h2V4c0-1.11-.9-2-2-2zm-8.03 7L11 6l-.97 3H7l2.47 1.76-.94 2.91 2.47-1.8 2.47 1.8-.94-2.91L15 9h-3.03z"/>
</SvgIcon>
);
ActionImportantDevices = pure(ActionImportantDevices);
ActionImportantDevices.displayName = 'ActionImportantDevices';
ActionImportantDevices.muiName = 'SvgIcon';
export default ActionImportantDevices;
|
files/rxjs/2.3.9/rx.compat.js | bonbon197/jsdelivr | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
result[i] = fun.call(thisp, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return {}.toString.call(arg) == arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable =
SerialDisposable = Rx.SerialDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var s = state;
var id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @private */
var CatchScheduler = (function (_super) {
function localNow() {
return this._scheduler.now();
}
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, _super);
/** @private */
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
/** @private */
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
/** @private */
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
/** @private */
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
/** @private */
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @private */
var ObserveOnObserver = (function (_super) {
inherits(ObserveOnObserver, _super);
/** @private */
function ObserveOnObserver() {
_super.apply(this, arguments);
}
/** @private */
ObserveOnObserver.prototype.next = function (value) {
_super.prototype.next.call(this, value);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.error = function (e) {
_super.prototype.error.call(this, e);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.completed = function () {
_super.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
if (!subject.isDisposed) {
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 Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function isIterable(o) {
return o[$iterator$] !== undefined;
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
function isCallable(f) {
return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isCallable(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var list = Object(iterable),
objIsIterable = isIterable(list),
len = objIsIterable ? 0 : toLength(list),
it = objIsIterable ? list[$iterator$]() : null,
i = 0;
return scheduler.scheduleRecursive(function (self) {
if (i < len || objIsIterable) {
var result;
if (objIsIterable) {
var next = it.next();
if (next.done) {
observer.onCompleted();
return;
}
result = next.value;
} else {
result = list[i];
}
if (mapFn && isCallable(mapFn)) {
try {
result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* 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;
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throw(new Error('Error'));
* var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
if (resource) {
disposable = resource;
}
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && observer.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
activeCount === 0 && observer.onCompleted();
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) { observer.onCompleted(); }
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) { observer.onCompleted(); }
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) {
throw new Error('Second observable is required');
}
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
self();
}, function () {
self();
}));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.do(observer);
* var res = observable.do(onNext);
* var res = observable.do(onNext, onError);
* var res = observable.do(onNext, onError, onCompleted);
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (!onError) {
observer.onError(err);
} else {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
*
* @example
* var res = source.takeLast(5);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while(q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
if (count <= 0) {
throw new Error(argumentOutOfRange);
}
if (arguments.length === 1) {
skip = count;
}
if (skip <= 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [],
createWindow = function () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
};
createWindow();
m.setDisposable(source.subscribe(function (x) {
var s;
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
var c = n - count + 1;
if (c >= 0 && c % skip === 0) {
s = q.shift();
s.onCompleted();
}
n++;
if (n % skip === 0) {
createWindow();
}
}, function (exception) {
while (q.length > 0) {
q.shift().onError(exception);
}
observer.onError(exception);
}, function () {
while (q.length > 0) {
q.shift().onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
return typeof selector === 'function' ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && observer.onNext(x);
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
}, thisArg);
}
return typeof selector === 'function' ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { 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 AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
docs/app/Examples/elements/List/Content/ListExampleImage.js | koenvg/Semantic-UI-React | import React from 'react'
import { List, Image } from 'semantic-ui-react'
const ListExampleImage = () => (
<List>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar2/small/rachel.png' />
<List.Content>
<List.Header as='a'>Rachel</List.Header>
<List.Description>Last seen watching <a><b>Arrested Development</b></a> just now.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar2/small/lindsay.png' />
<List.Content>
<List.Header as='a'>Lindsay</List.Header>
<List.Description>Last seen watching <a><b>Bob's Burgers</b></a> 10 hours ago.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar2/small/matthew.png' />
<List.Content>
<List.Header as='a'>Matthew</List.Header>
<List.Description>Last seen watching <a><b>The Godfather Part 2</b></a> yesterday.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar/small/jenny.jpg' />
<List.Content>
<List.Header as='a'>Jenny Hess</List.Header>
<List.Description>Last seen watching <a><b>Twin Peaks</b></a> 3 days ago.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='http://semantic-ui.com/images/avatar/small/veronika.jpg' />
<List.Content>
<List.Header as='a'>Veronika Ossi</List.Header>
<List.Description>Has not watched anything recently</List.Description>
</List.Content>
</List.Item>
</List>
)
export default ListExampleImage
|
geonode/contrib/monitoring/frontend/src/components/organisms/alert-list/index.js | ingenieroariel/geonode | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import CircularProgress from 'material-ui/CircularProgress';
import SettingsIcon from 'material-ui/svg-icons/action/settings';
import HoverPaper from '../../atoms/hover-paper';
import Alert from '../../cels/alert';
import actions from './actions';
import styles from './styles';
const mapStateToProps = (state) => ({
alerts: state.alertList.response,
interval: state.interval.interval,
status: state.alertList.status,
timestamp: state.interval.timestamp,
});
@connect(mapStateToProps, actions)
class AlertList extends React.Component {
static contextTypes = {
router: PropTypes.object.isRequired,
}
static propTypes = {
alerts: PropTypes.object,
get: PropTypes.func.isRequired,
interval: PropTypes.number,
status: PropTypes.string,
timestamp: PropTypes.instanceOf(Date),
}
constructor(props) {
super(props);
this.handleClick = () => {
this.context.router.push('/alerts/settings');
};
this.get = (interval = this.props.interval) => {
this.props.get(interval);
};
}
componentWillMount() {
this.get();
}
render() {
const rawAlerts = this.props.alerts;
let alerts;
if (this.props.status === 'pending') {
alerts = (
<div style={styles.spinner}>
<CircularProgress size={80} />
</div>
);
} else {
alerts = rawAlerts && rawAlerts.data && rawAlerts.data.problems.length > 0
? rawAlerts.data.problems.map((alert, index) => (
<Alert
key={index}
alert={alert}
/>
))
: [];
}
return (
<HoverPaper style={styles.content}>
<div style={styles.header}>
<h3>Alerts</h3>
<RaisedButton
onClick={this.handleClick}
style={styles.icon}
icon={<SettingsIcon />}
/>
</div>
{alerts}
</HoverPaper>
);
}
}
export default AlertList;
|
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-youtube/7.4.0/test/helpers/shallowRender.js | Akkuma/npm-cache-benchmark | /**
* Module dependencies
*/
import React from 'react';
import TestUtils from 'react-dom/test-utils';
import setupYouTube from './setupYouTube';
/**
* Helper for testing the output of a component's `render` method
*
* @param {Object} [props] - component instance props
* @returns {Object}
*/
const shallowRender = (props) => {
const { YouTube } = setupYouTube();
const renderer = TestUtils.createRenderer();
renderer.render(<YouTube { ...props } />);
const output = renderer.getRenderOutput();
return {
props,
output,
};
};
export default shallowRender;
|
sites/all/themes/custom/gbifadmin/bootstrap/js/tests/vendor/jquery.min.js | gbif/gbif-drupal | /*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;
return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){
return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m});
|
src/components/Overlay/Content.js | u-wave/web | import cx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
const OverlayContent = ({
className,
children,
}) => (
<div className={cx('Overlay-content', className)}>
{children}
</div>
);
OverlayContent.propTypes = {
className: PropTypes.string,
children: PropTypes.node.isRequired,
};
export default OverlayContent;
|
src/FormControls/Static.js | dongtong/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import InputBase from '../InputBase';
import childrenValueValidation from '../utils/childrenValueInputValidation';
class Static extends InputBase {
getValue() {
const {children, value} = this.props;
return children ? children : value;
}
renderInput() {
return (
<p {...this.props} className={classNames(this.props.className, 'form-control-static')} ref="input" key="input">
{this.getValue()}
</p>
);
}
}
Static.propTypes = {
value: childrenValueValidation,
children: childrenValueValidation
};
export default Static;
|
examples/src/components/Footer.js | krasimir/hocbox | import React from 'react';
import { wire, signal } from '../../../lib';
class Footer extends React.Component {
render() {
const { all, done } = this.props;
const latestAddedTodo = this.props['new-todo'];
return (
<div className='footer'>
<span>Done: { `${ done } / ${ all }` }</span>
<span>Latest: { latestAddedTodo === true ? '...' : latestAddedTodo }</span>
</div>
);
}
}
export default wire(
signal(Footer, ['new-todo']),
['store'],
store => ({
all: store.getTodos().length,
done: store.getTodos().filter(todo => todo.done).length
})
); |